1

Hope someone can help this is driving me made.

Can anybody tell me what is wrong with this select, It currently does the search properly but it checks every result in "Galleries" rather than just the ones in "category: summer" and "Status: used".

So what i want it to do is search for the keywords ($find) only if they are in category "summer" and Status "used". Any ideas what i need to do. Lol ill take anything at this point. stressed :)

$result = mysql_query("
  SELECT
     Gallery_URL,
     Thumbnail_URL,
     Nickname,
     Description 
  FROM Galleries
  WHERE 
    Category = 'summer' 
    AND Status = 'Used'
    AND Nickname LIKE '%$find1%'
    OR Nickname LIKE '%$find2%'
    OR Nickname LIKE '%$find3%'
    OR Description LIKE '%$find1%'
    OR Description LIKE '%  $find2%'
    OR Description LIKE '%$find3%'
  LIMIT 0 , 10");
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
mark
  • 39
  • 4

3 Answers3

1

Add parentheses like this:

SELECT Gallery_URL, Thumbnail_URL, Nickname, Description 
FROM Galleries  
WHERE 
   Category = 'summer' 
   AND Status = 'Used' 
   AND (Nickname LIKE '%$find1%' 
   OR Nickname LIKE '%$find2%' 
   OR Nickname LIKE '%$find3%' 
   OR Description LIKE '%$find1%' 
   OR Description LIKE '%  $find2%' 
   OR Description LIKE '%$find3%')
sashkello
  • 17,306
  • 24
  • 81
  • 109
1

You are shortcircuiting the AND and OR operators. Try to isolate the OR by placing them in a group,

SELECT  Gallery_URL, 
        Thumbnail_URL, 
        Nickname,
        Description 
FROM    Galleries 
WHERE   Category = 'summer' AND 
        Status = 'Used' AND 
        (
            Nickname LIKE '%$find1%' OR 
            Nickname LIKE '%$find2%' OR 
            Nickname LIKE '%$find3%' OR 
            Description LIKE '%$find1%' OR 
            Description LIKE '% $find2%' OR 
            Description LIKE '%$find3%' 
        )
LIMIT   0 , 10

As a sidenote, the query is vulnerable with SQL Injection if the value(s) of the variables came from the outside. Please take a look at the article below to learn how to prevent from it. By using PreparedStatements you can get rid of using single quotes around values.

Community
  • 1
  • 1
John Woo
  • 258,903
  • 69
  • 498
  • 492
0

Try grouping the expressions in your where clause. For example

$result = mysql_query("SELECT Gallery_URL, Thumbnail_URL
, Nickname, Description 
FROM Galleries 
WHERE Category = 'summer' 
AND Status = 'Used' 
AND (Nickname LIKE '%$find1%' 
OR Nickname LIKE '%$find2%' 
OR Nickname LIKE '%$find3%' 
OR Description LIKE '%$find1%' 
OR Description LIKE '% $find2%' 
OR Description LIKE '%$find3%') 
LIMIT 0 , 10");
Dan Bracuk
  • 20,699
  • 4
  • 26
  • 43