即時創建一個搜索功能,將允許用戶輸入一個問題,然後我的代碼將匹配儘可能多的單詞與我的MySQL數據庫中已有的問題,並顯示前5個結果,具體取決於單詞數量在問題中匹配。如何對代碼的結果進行排序?
我使用count(
)函數來計算匹配詞的數量,但是此刻顯示的結果顯示爲數據庫中前50個詞匹配度超過50%的結果。我希望結果顯示爲最高的比賽第一和工作的方式下來每個結果在數據庫中,但只顯示前5 這裏是代碼我有
<?php
include("config.php");
$search_term = filter_var($_GET["s"], FILTER_SANITIZE_STRING); //User enetered data
$search_term = str_replace ("?", "", $search_term); //remove any question marks from string
$search_count = str_word_count($search_term); //count words of string entered by user
$array = explode(" ", $search_term); //Seperate user enterd data
foreach ($array as $key=>$word) {
$array[$key] = " title LIKE '%".$word."%' "; //creates condition for MySQL query
}
$q = "SELECT * FROM posts WHERE " . implode(' OR ', $array); //Query to select data with word matches
$r = mysql_query($q);
$count = 0; //counter to limit results shown
while($row = mysql_fetch_assoc($r)){
$thetitle = $row['title']; //result from query
$thetitle = str_replace ("?", "", $thetitle); //remove any question marks from string
$title_array[] = $thetitle; //creating array for query results
$newarray = explode(" ", $search_term); //Seperate user enterd data again
foreach($title_array as $key => $value) {
$thenewarray = explode(" ", $value); //Seperate each result from query
$wordmatch = array_diff_key($thenewarray, array_flip($newarray));
$result = array_intersect($newarray, $wordmatch);
$matchingwords = count($result); //Count the number of matching words from
//user entered data and the database query
}
if(mysql_num_rows($r)==0)//no result found
{
echo "<div id='search-status'>No result found!</div>";
}
else //result found
{
echo "<ul>";
$title = $row['title'];
$percentage = '.5'; //percentage to take of search word count
$percent = $search_count - ($search_count * $percentage); //take percentage off word count
if ($matchingwords >= $percent){
?>
<li><a href='<?php echo $row['url']; ?>'><?php echo $title ?><i> No. matching words: <?php echo $matchingwords; ?></i></a></li>
<?php
$count++;
if ($count == 5) {break;
}
}else{
}
}
echo "</ul>";
}
?>
下圖顯示的是什麼當我在搜索欄中搜索「如何製作我自己的網站」時會發生這種情況。我在數據庫中已經有幾個測試問題,這些問題都是類似的問題,最後一項與我提問的問題完全匹配,但由於它目前將它們顯示爲前5個結果,它忽略了完全匹配。 以下是該搜索的結果。
我已經添加了一些代碼,顯示每個問題中有多少個單詞匹配,所以您可以看到它的工作更好一點。另外它的巧合在於其升序,它顯示數據庫中的前5個匹配結果。
我需要添加什麼代碼才能安排它,以便顯示與整個數據庫最接近的匹配,然後是第二最佳匹配,第三等...?
** WARNING **你的代碼容易受到SQL注入攻擊! – 2012-08-04 13:44:50
請問您是否願意解釋Daniel A. White? – Ben 2012-08-04 13:46:31
您的代碼正在將查詢字符串中的內容刪除,但將它加入查詢中。 – 2012-08-04 13:47:55