简体   繁体   English

php mysql查询根据匹配关键字的密度返回结果

[英]php mysql query to return results based on density of keywords matched

I have a form which allows users to search a database table for recipes, they can either type the name of the recipe they are looking for or they can type in some keywords. 我有一个允许用户在数据库表中搜索配方的表格,他们可以输入要查找的配方名称,也可以输入一些关键字。

I am trying to figure out how i can check the records titles and return them based on the % density of keywords. 我试图弄清楚如何检查记录标题并根据关键字的%密度返回它们。 so say the user searched "sweet and sour chicken" the results would find all the recipes which matched all the words first, then all the recipes with 3 of the words, then 2, then 1. Hope that makes sense :) 因此,假设用户搜索“糖醋鸡”,结果将首先找到与所有单词匹配的所有食谱,然后是所有包含3个单词的食谱,然后是2个,然后是1个。希望这是有意义的:)

here is what i have 这是我所拥有的

$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);  

which checks the titles that match each of the keywords but it doesn't find out the density of the keywords in the title. 它会检查与每个关键字匹配的标题,但不会找出标题中关键字的密度。 Can anyone help me with this, i'm stumped! 有人可以帮我吗,我很沮丧!

Many Thanks 非常感谢

Try this: 尝试这个:

$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;";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM