I've created a query that grabs fairly short strings from the database based on keywords created by the user (credit to zhikharev for his answer):
$searchArray = explode(' ', $search);
$searchNumber = count($searchArray);
$query = "SELECT * FROM tags WHERE tags.tag LIKE CONCAT('%',?,'%')" .
str_repeat(" OR tags.tag LIKE CONCAT('%',?,'%')", $searchNumber - 1);
$stmt = $mysqli -> prepare($query);
$bind_names[] = str_repeat('s', $searchNumber);
for ($i = 0; $i < count($searchArray); $i++){
$bind_name = 'bind'.$i; /*generate a name for variable bind1, bind2, bind3...*/
$$bind_name = $searchArray[$i]; /*create a variable with this name and put value in it*/
$bind_names[] = & $$bind_name; /*put a link to this variable in array*/
}
call_user_func_array(array($stmt, 'bind_param'), &$bind_names);
$stmt -> execute();
My problem is that I don't know how to sort this result by relevancy. Note that one tag in the database can contain multiple words.
Let's say that the user searches for "New York City". Then in the database I have:
New York
York
New York City
New Zealand
Kansas City
I would like the result to look like this:
New York City
New York
New Zealand
York
Kansas City
It should look for tags with most matches with the words in the user input and tags that have approximately the same word order as the order of the words in the search.