Select with Search conditions

Asked

Viewed 191 times

1

I need to make a query where 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 the way above did not work, it normally displays the data as the survey but also displays the data that is not of the same parameter (users that are not active).

  • 2

    Play a parentheses after the WHERE and close it before the AND, see if it is the desired result.

1 answer

3


You need to specify the order in which the criteria will be evaluated using the (), 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 among logical operators OR and AND (the latter has priority).

To OR B OR C AND D - First will solve "C AND D" and then A OR B OR "result C AND D".

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

( To OR B OR C ) AND D

  • 2

    was exactly that, thank you guys!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.