我有一个允许用户在数据库表中搜索食谱的表单,他们可以键入他们要查找的食谱的名称,也可以键入一些关键字。
我试图找出如何检查记录标题并根据关键字的密度百分比返回它们。所以说用户搜索“糖醋鸡”结果会找到所有的食谱首先匹配所有的单词,然后所有的食谱与3个单词,然后2,然后1.希望有意义:))
这是我的
$keywords = mysqli_real_escape_string($con,$_POST['recipe-search']);
$search_keywords = str_replace("and", "",$keywords);
//Find The Latest Recipies
$searchTerms = explode(' ', $search_keywords);
$searchTermBits = array();
foreach ($searchTerms as $term)
{
$term = trim($term);
if (!empty($term))
{
$searchTermBits[] = "title LIKE '%$term%'";
}
}
$q = "SELECT * FROM tbl_recipes WHERE ".implode(' OR ', $searchTermBits);
检查与每个关键字匹配的标题,但不会找出标题中关键字的密度。任何人都可以帮助我,我很难过!
非常感谢
答案 0 :(得分:1)
试试这个:
$keywords = mysqli_real_escape_string($con,$_POST['recipe-search']);
$search_keywords = preg_replace('/\s{1,}(and\s*)*/', ' ', $keywords);;
//Find The Latest Recipies
$searchTerms = explode(' ', $search_keywords);
$likeStr = "`title` LIKE '%" . implode("%' OR `title` LIKE '%", $search_terms) . "%'";
$q = "SELECT *,(SELECT COUNT(*) FROM `tbl_recipes` WHERE ". $likeStr ." GROUP BY `title`) as `count` FROM `tbl_recipes` WHERE ". $likeStr .") ORDER BY `count` DESC;";