Jump to content

Searching multiple columns for multiple words


prw

Recommended Posts

Hello all! I'm having some issues with a snippet that I found online and have edited to how I want it.

 

Basically the code works at the moment, except if I were to search for 2 or 3 terms, it would search the columns username/action/result/changes for any result that have any of the words rather than results that include both terms, instead of either.

 

I want the query to be like (assuming 2 search terms):

 

username LIKE '%$filter%' OR action LIKE '%$filter%' OR result LIKE '%$filter%' OR changes LIKE '%$filter%' AND username LIKE '%$filter%' OR action LIKE '%$filter%' OR result LIKE '%$filter%' OR changes LIKE '%$filter%'

 

and not:

 

username LIKE '%$filter%' OR action LIKE '%$filter%' OR result LIKE '%$filter%' OR changes LIKE '%$filter%' OR username LIKE '%$filter%' OR action LIKE '%$filter%' OR result LIKE '%$filter%' OR changes LIKE '%$filter%'

 

It needs an AND instead of an OR, but I'm not sure how to go around doing it.

 

Here's the code as it is at the moment:

 

$filter = ($_POST['filter']); 

$query = "SELECT * FROM activity WHERE"; 

$searchresult = explode(" ", $filter); 

     foreach ($searchresult as $key => $filter) { 
$query .= " username LIKE '%$filter%' OR action LIKE '%$filter%' OR result LIKE '%$filter%' OR changes LIKE '%$filter%'"; 
     if ($key != (sizeof($searchresult) - 1))   
$query .= " AND ";
     }
$query .= "ORDER BY id DESC"; 

 

Sorry if this is a little confusing to understand, hope someone understands what I need. :)

Link to comment
Share on other sites

It sounds like you just need to surround the "or" parts with parenthesis.

 

(username LIKE '%$filter%' OR action LIKE '%$filter%' OR result LIKE '%$filter%' OR changes LIKE '%$filter%') AND (username LIKE '%$filter%' OR action LIKE '%$filter%' OR result LIKE '%$filter%' OR changes LIKE '%$filter%')

 

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.