我有一个根据在搜索框中输入的关键字搜索数据库条目的查询。
// function to get search keywords from url
$q = furl($_GET['q']);
$sExp = preg_split('/\s+/',$q);
$secure_keywords = array();
foreach ($sExp as $key=>$keyword){
if (strlen($keyword) >= 3){
// cut off words that are less than 3 chars
$secure_keywords[] = $keyword;
}
}
$kwords = count($secure_keywords);
foreach ($secure_keywords as $key=>$keyword)
{
// function to prevent sql injection
$keyword = sql_proof($keyword);
$query="SELECT * FROM listings WHERE MATCH (meta_keywords) AGAINST ('$keyword' IN BOOLEAN MODE) ORDER BY id";
}
当使用 2 个或更多单词时,如果至少有 1 个单词拼写错误,则查询将不会返回任何结果(即使输入的关键字中的其余单词确实存在结果)。例如,我输入单词“good”,我至少得到 1 个结果,但如果我使用“good point”,查询不会返回任何结果,因此它完全忽略单词“good”的匹配结果。 如果输入的关键字中至少有 1 个匹配单词,是否有办法让查询匹配结果?谢谢
不要使用“布尔模式”尝试
SELECT * FROM articles WHERE MATCH (title, body) AGAINST ('database test')
即使数据库后面没有“test”之类的单词,它也会返回结果
SELECT * FROM tablename WHERE MATCH (col1, col2) AGAINST ('string to be searched')
查看以下解决方案,了解将结果与所使用的任何关键字进行匹配的方法。另请查看文档以获取有关运算符和布尔 fst 的更多信息http://dev.mysql.com/doc/refman/5.1/en/fulltext-boolean.html
// function to get search keywords from url
$q = furl($_GET['q']);
$sExp = preg_split('/\s+/',$q);
$secure_keywords = array();
foreach ($sExp as $key=>$keyword){
if (strlen($keyword) >= 3){
// cut off words that are less than 3 chars
$secure_keywords[] = $keyword;
}
}
$kwords = count($secure_keywords);
//init empty keywords array
$keywords = array();
//secure all keywords
$keywords = array_map(function($item){ return sql_proof($item); }, $secure_keywords);
//implode the words with a space between
$keywords = implode(" ",$keywords);
//just one query with match against ANY of the words from initial keyword array
$query="SELECT * FROM listings WHERE MATCH (meta_keywords) AGAINST ('$keywords' IN BOOLEAN MODE) ORDER BY id";