As I haven’t posted a tutorial in a while, sorry about that, I decided I would show you all how to change a standard LIKE MySQL query into a query that will find all words in the query in any order.

Normally you would have a MySQL query that looks like this:

SELECT column FROM table WHERE column LIKE '%word1 word2%'

This would only find word1 and word2 in that order. If you want to change this you need to make a few changes to the PHP code that sorts your query.

When you get your query from your search, do whatever SQL injection prevention you need to and then take your query and run it through explode like this:

$words = explode(' ', $searchquery);

This will return an array of your search words separated into an array by the spaces. Now you just need to create your MySQL query:

$sql = "SELECT column FROM table WHERE";
$sql_end = '';
foreach($words as $word) {
    $sql_end .= " AND column LIKE '%{$word}%''';
}
$sql_end = substr($sql_end, 4);
$sql = $sql.$sql_end;
$result = $mysqli->query($sql);
//continue

That will then make a query that looks like this (assuming there are 2 words):

SELECT column from table WHERE column LIKE '%word1%' AND column LIKE '%word2%'

That will then find the words in any order. I would imagine, although I haven’t tried this, you could make the words optional by using the OR operator, this will then return the results if only some of the results are found where AND requires then all to be found or it will not return a result.

I hope this little tutorial has been some use to you guys & gals out there. Also I’ll be doing some screen cast style tutorials in the near future, so look out for them.