简体   繁体   中英

PHP MYSQL Search for best result

I need to Search Allthrough my database using PHP and MYSQL code , What i have done for now is

$mysearch = $_GET['search'];//the search query , for ex - best potato
$recepiesuisine_quer = mysql_query("SELECT * FROM addrecepie WHERE  MATCH (name,method,contributedby,ingredients,healthytip,cuisine) AGAINST ('".$mysearch."' IN BOOLEAN MODE) ");
// Here the MATCH contain all the columns of my table
             while($row = mysql_fetch_assoc($recepiesuisine_quer)) {
             echo" 
                <a href='recepie_detail.php?id=".$row['id']."&cuisine=".$row['cuisine']."' id='foodie1_title' class='span-7'>
                <div class='span-1'><img src='".$row['image']."' width='80'></div>
                <div class='span-5'>
                    ".$row['name']." ,<br /> ".$row['contributedby'].",<br /> ".$row['cuisine']." <br />
                </div>
                </a>
             ";
             }

My Search is working fine for single character , but as if i want to search 2 characters , for ex :- Best Potato it will give me the result of

  1. All Potato anywhere in the table rows.

  2. All Best anywhere in the table rows.

  3. All Best Potato anywhere in the table rows.

I want my 3rd condition to be display at first and then after it may show 1st and 2nd result. I need to show the most related item first. With the above query i am unable to do so. Please Help me what query should i use.

You could use this query -

SELECT * 
FROM addrecepie 
WHERE  MATCH (name,method,contributedby,ingredients,healthytip,cuisine) 
       AGAINST ('".$mysearch."' IN BOOLEAN MODE) 
OR MATCH (name,method,contributedby,ingredients,healthytip,cuisine) 
       AGAINST (SUBSTRING_INDEX('".$mysearch."', ' ', 1) IN BOOLEAN MODE)
OR MATCH (name,method,contributedby,ingredients,healthytip,cuisine) 
       AGAINST (SUBSTRING_INDEX('".$mysearch."', ' ', -1) IN BOOLEAN MODE)  

The SUBSTRING_INDEX() function would split the words with a space. This is for 2 words with 1 space. You might have to use the TRIM() function as well.

总是绑定您的变量,否则mysql查询将失败,以防它们是搜索参数值中的单引号。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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