【发布时间】:2012-08-04 13:35:54
【问题描述】:
我正在创建一个允许用户输入问题的搜索功能,然后我的代码会将尽可能多的单词与我的 MySQL 数据库中已有的问题匹配,并根据单词的数量显示前 5 个结果在问题中匹配。
我使用count() 函数来计算匹配单词的数量,但是目前显示的结果显示为数据库中具有 50% 或更多单词匹配的前 5 个结果。我希望首先将结果显示为最高匹配,然后逐步降低数据库中的每个结果,但只显示前 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 个匹配结果。
我需要添加什么代码来排列它,以便它首先显示整个数据库中最接近的匹配,然后是第二个最佳匹配,第三个等等...?
【问题讨论】:
-
警告您的代码容易受到 sql 注入攻击!
-
您愿意进一步解释一下 Daniel A. White 吗?
-
您的代码正在从查询字符串中删除内容,但将其直接加入到查询中。
-
是的,但它只将它加入到 WHERE 子句中,另外我还可以添加额外的代码来检查以确保只有字母和数字已输入到字符串中。但是谢谢你告诉我
-
请不要使用
mysql_*函数编写新代码。它们不再维护,社区已经开始deprecation process。看到 red box 了吗?相反,您应该了解prepared statements 并使用PDO 或MySQLi。如果你不能决定哪一个,this article 会帮助你。如果你选择 PDO,here is good tutorial.