I have two seperate queries for my database which return search results for two different types of data which are displayed seperately on the search results page.
The two groups displayed are “contacts” and “customers”. Customers are contacts in the database that have been given a contact number that is NOT zero!
This is a normal query which does not use any LIKE statements within the query.
$contacts = $db->query("SELECT DISTINCT contact.id, first_name, second_name, company_name, email FROM contact INNER JOIN contact_quote WHERE customer_id = 0 GROUP BY first_name, second_name, company_name, email, quote_name ");
$customers = $db->query("SELECT DISTINCT contact.id, first_name, second_name, company_name, email FROM contact INNER JOIN contact_quote WHERE customer_id != 0 GROUP BY first_name, second_name, company_name, email, quote_name ");
It works fine and displays results into their correct categories.
Like so

However My new query which is this
$contacts = $db->query("SELECT DISTINCT contact.id, first_name, second_name, company_name, email FROM contact INNER JOIN contact_quote WHERE customer_id =0 AND first_name LIKE '%$search%' OR second_name LIKE '%$search%' OR company_name LIKE '%$search%' OR email LIKE '%$search%' OR quote_name LIKE '%$search%' AND contact.id = contact_quote.cid GROUP BY first_name, second_name, company_name, email, quote_name");
$customers = $db->query("SELECT DISTINCT contact.id, first_name, second_name, company_name, email FROM contact INNER JOIN contact_quote WHERE customer_id !=0 AND first_name LIKE '%$search%' OR second_name LIKE '%$search%' OR company_name LIKE '%$search%' OR email LIKE '%$search%' OR quote_name LIKE '%$search%' AND contact.id = contact_quote.cid GROUP BY first_name, second_name, company_name, email, quote_name");
Displays all results in both lists even if they are NOT A Customer
Screenshot:

Im guessing there is something wrong in the new query in which It is not able to compare correctly if the column “customer_id” is not equal to zero and is displaying everything?
To summarise I want to do this:
- Compare with search string
- If any contacts match the search string put them in the contacts query result
- If any customers match the search string put them in the customers query result.
Thanks
You need parenthesis around your LIKE statements. It’s getting to your
WHEREclause, checks forcustomer_id=0 AND first_name LIKE '%$search%'and then the next it checksOR second_name LIKE '%$search'and it won’t matter ifcustomer_id=0because it’s only checking the one case now. By putting the parens around it, it will checkcustomer_id=0and then all the LIKES.