Do you have a lot of content or data from your website in a MySQL database, but no search feature to surface it? This is a simple function that performs searches better than just using the LIKE operator in your SELECT statement.
This is a handy function that takes that name of the table that you want to search, the number of words in the query as well the words that user entered (the query itself as an array of word). It runs a select query on all the rows in that table. The num_results tells us the number of the results we got out of that select statement, and then the for loop determines the relevancy of each result and ranks them accordingly.
function query_table ($tablename, $q_num, $q_array) {
$query = "SELECT number, article from $tablename";
$result = mysql_query($query);
$num_results = mysql_num_rows($result);
for ($c = 0;$c < $num_results; $c++) {
$relevancy = 0;
$row = mysql_fetch_object($result);
$mypage = $row->number;
$mycontent = strtolower(strip_tags($row->article));
for ($d = 0; $d < $q_num; $d++) {
$relevancy += substr_count($mycontent, strtolower(strip_tags($q_array[$d])));
}
}
if ($relevancy>0)
$res["$mypage"] = $relevancy;
if (count($res)>0)
arsort ($res);
return $res;
}
Sign up for our daily email newsletter:
You must log in to post a comment.