mysqli query, LIKE and AND in the same query doesn't work out like it should

StackOverflow https://stackoverflow.com/questions/1824962

  •  22-07-2019
  •  | 
  •  

Question

so this is my query, it doesn't matter if approved is set to 0 or 1 it will give me all the rows anyway

SELECT * 
FROM `tutorials` 
WHERE tags LIKE '% php %' OR tags LIKE 'php %' OR tags LIKE '% php' OR tags = 'php' 
AND approved=1

I guess it's because of the OR but I might be wrong, if someone could help me out on this :)

Was it helpful?

Solution

Try brackets

SELECT * 
FROM `tutorials` 
WHERE   (       tags LIKE '% php %' 
            OR  tags LIKE 'php %' 
            OR  tags LIKE '% php' 
            OR  tags = 'php' 
        )
AND approved=1

OTHER TIPS

I think you are missing some colons:

SELECT * 
FROM `tutorials` 
WHERE (tags LIKE '% php %' OR tags LIKE 'php %' OR tags LIKE '% php' OR tags = 'php')
AND approved=1

The reason you should include colons, is because OR and AND operators are on the same level of precedence. When you omit the colons, your query would be parsed as:

SELECT * 
FROM `tutorials` 
WHERE (tags LIKE '% php %' OR (tags LIKE 'php %' OR (tags LIKE '% php' OR (tags = 'php' 
AND approved=1))))

Especially when using long lists of OR and AND operators in a query, it is advisable to use colons to make your intent clear. For a full list of the operator precedence in MySQL (which is generally common to other SQL dialects), see the MySQL manual.

I didnt get what you exactly want. But this may be the one that you are looking for

SELECT * FROM tutorials WHERE ( tags LIKE '% php %' OR tags LIKE 'php %' OR tags LIKE '% php' OR tags = 'php' ) AND approved=1

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top