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



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 :)


Solution:1

Try brackets

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


Solution:2

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.


Solution:3

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


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »