Select with Search Terms

1

I need to make an query where I only display results in one condition:

# Search the Database
$select_sql = "SELECT * FROM users WHERE user LIKE :search OR date_access LIKE :search OR ip LIKE :search AND active LIKE :active ORDER BY id DESC";
$select_db = $connect->prepare($select_sql);
$select_db->bindValue(':search', "%{$search_user}%");
$select_db->bindValue(':active', "yes");
$select_db->execute();

However, in the above way it did not work, it normally displays the data according to the search, but it also displays data that is not of the same parameter (users that are not active).

    
asked by anonymous 14.09.2016 / 21:49

1 answer

3

You need to specify the order that the criteria will be evaluated using () , as @rray commented.

SELECT * FROM users 
WHERE (user LIKE :search OR date_access LIKE :search OR ip LIKE :search ) 
AND active LIKE :active ORDER BY id DESC

MySQL works with priorities between logical operators OR and AND (the latter has priority).

A OR B% with% C OR D - First it will solve "C AND D" and then A AND B% with% "result C AND D".

In your case, you need to specify that the "OR" criteria must first be evaluated.

OR D

    
14.09.2016 / 22:15