I'm building a basic search function for my site. Realising that the most useful search displays the page with the most counts of the terms given, I coded the following:
function search()
{
$this->page = preg_replace('/[^\w \"\']/i', '', trim($this->page));
preg_match_all('/"(.[^"]+)"|([\w]+)/i', $this->page, $terms);
$terms=array_unique($terms[0]); // scrub duplicate search terms
$tsql="SELECT reviewSummary, reviewFullText, game.gameName FROM review LEFT JOIN game ON review.gameID = game.gameID ";
$constraint="WHERE";
foreach ($terms as $term)
{
$term=str_replace('"','',$term);
$tsql.=" $constraint (reviewSummary LIKE '%".$term."%' OR reviewFullText LIKE '%".$term."%' OR game.gameName LIKE '%".$term."%')";
$constraint="AND";
}
$tsql .= "AND game.isPublished = 'y'";
$result = $this->sql->db_query($tsql);
if (mysql_num_rows($result)!=0)
{
while($row = mysql_fetch_array($result))
{
$gameName = stripslashes($row['gameName']);
$content = strip_tags($row['reviewFullText']) . ' ' . $row['reviewSummary'];
$counter = 0;
foreach($terms as $term)
{
$term=str_replace('"','',$term);
preg_match_all("/($term)/i", $content, $matches);
foreach($matches[0] as $m)
{
$counter++;
}
}
$found["Games"][$gameName]=$counter;
}
}
print_r($found);
}
Works great. What it doesn't do is order the results in according to which has the most matches. I'm not sure how to sort the resulting array to achieve this, can anyone help?