views:

15

answers:

2

Hello everyone,

I have a simple query as listed below

SELECT id, name, email FROM users WHERE group_id = 1

This works great until, I then start adding LIKE queries, chained with OR statements to the end.

SELECT id, name, email FROM users 
 WHERE group_id = 1 
   AND id LIKE $searchterm 
    OR name LIKE $searchterm 
    OR email LIKE $searchterm

Suddenly my WHERE clause is no longer upheld and results with a 'group_id' of 2 or 3 are retrieved.

Is there a way I can group WHERE clauses so that they are always upheld or am I missing something obvious?

+1  A: 

I assume you want

email FROM users WHERE group_id = 1 AND (id LIKE $searchterm OR name LIKE $searchterm OR email LIKE $searchterm)

Here is the mysql operator precedence table

deinst
Cheers, I have bookmarked it for future reference
Tim
+2  A: 

Dealing with the query first - you need to use brackets for the WHERE clause to be interpreted correctly:

SELECT id, name, email 
  FROM users 
 WHERE group_id = 1 
   AND (    id LIKE $searchterm 
       OR name LIKE $searchterm 
       OR email LIKE $searchterm)

I'd be looking at using Full Text Search (FTS) instead, so you could use:

SELECT id, name, email 
  FROM users 
 WHERE group_id = 1 
   AND MATCH(id, name, email) AGAINST ($searchterm)

Mind that the USERS table needs to be MyISAM...

OMG Ponies
Thankyou very much:)
Tim