I’m trying to mod a search routing, i have two fields, artist & title, when i search for example Foo Fighters the pretender, i don’t get any results, whereas if i search individually i do. Any help would be much appreciated thanks.
$arraySearch = explode(" ", $searchvalue);
$arrayFields = array(0 => "Artist", 1 => "Title");
$countSearch = count($arraySearch);
$a = 0;
$b = 0;
$query = "SELECT * FROM ".$table." WHERE (";
$countFields = count($arrayFields);
while ($a < $countFields)
{
while ($b < $countSearch)
{
$query = $query."$arrayFields[$a] LIKE '%$arraySearch[$b]%'";
$b++;
if ($b < $countSearch)
{
$query = $query." AND ";
}
}
$b = 0;
$a++;
if ($a < $countFields)
{
$query = $query.") OR (";
}
}
$query = $query.")";
$query_result = mysql_query($query);
echo '<h1>Your Search Results</h1>'."\n\n";
if(mysql_num_rows($query_result) < 1)
{
echo '<p>No matches found for "'.$searchvalue.'"</p>';
}
else
{
echo '<p>Search Results for "'.$searchvalue.'":</p>'."\n\n";
while($row = mysql_fetch_assoc($query_result))
{
// output
}
}
This search function is very inefficient. Since you are searching on a wildcard
%blah%, it has to do a full table scan to find any records. That is, if you have 1 million records, it has to read all 1 million records in order to find your search results. On a busy site with a large table, this can kill your performance and database server.If you are using the MyISAM engine for the table, I would recommend adding a FULLTEXT index to the artist and title columns and then performing a fulltext search like this:
As written by the OP, here is a query that sorts by match relevance on the search query