Search code examples
mysqlsqlwhere-clauseoperator-precedence

How do I use AND and OR in a single statement


This is my SQL and data is feed by PHP

SELECT COUNT(*) FROM table 
WHERE approve='true' AND `description`like '%".$name."%' OR  `name`like '%".$name."%' OR `location` like '%".$location."%'

I am able to view records where approve is false when I process this query.


Solution

  • Probably the ORed conditions should go into parentheses:

    SELECT COUNT(*) 
    FROM table 
    WHERE 
        approve = 'true' 
        AND (
            `description` like CONCAT('%', :name, '%') 
            OR  `name`    like CONCAT('%', :name, '%') 
            OR `location` like CONCAT('%', :location, '%') 
        )