SQL“LIKE”选择器在我的搜索引擎中的作用类似于“=”

时间:2017-03-03 07:05:51

标签: php search-engine

我已经创建了一个简单的搜索引擎来显示数据库的结果,但是我需要它来显示所有带有相似字符的结果,而不是整个确切的单词。例如用户类型eng--它应该返回结果引擎和所有其他单词都带有eng,但是目前只有当你输入整个单词时才会返回一些内容。引擎。我在某个地方有一个错误但是找不到它:有我的代码。

<?php

$fsearch = "";
if (!empty($_GET['fsearch'])){

$fsearch=$_GET['fsearch'];

$query = "SELECT * FROM food_data_bg WHERE ";
$terms = explode (" ",$fsearch);
$i=0;
foreach($terms as $each){
      $i++;
     if($i == 1){
       $query .= "title LIKE '$each'";
     }
else{
      $query .= "OR title LIKE '$each'";
     }
}

     $hostname = "localhost";
     $username = "name";
     $password = "pass";
     $databaseName = "dbName";
     $connect = new mysqli($hostname, $username, $password, $databaseName);
     $connect->set_charset("utf8");
       $query = mysqli_query($connect,$query);

       $num_rows = mysqli_num_rows($query);
          if($num_rows > 0){
            while($row = mysqli_fetch_assoc($query)){
               $title = $row["title"];
               $fimage = $row["fimage"];
               $carbs = $row["carbohydrates"];
               $fats = $row["fats"];
               $proteins = $row["proteins"];
               $CaloriesTotal = $row["calories total"];
              echo "
                    <table id='table1'>
                    <tbody>
                    <tr class='Table1-row2'>
                    <td><a><img src='$fimage'</a></td>
                    <td>$title</td>
                    <td>$carbs</td>
                    <td>$fats</td>
                    <td>$proteins</td>
                    <td>$CaloriesTotal</td>
                    </tr>
                    </tbody>
                    </table>";
                    }
                 } //got "else" claim here,but i don't think the mistake is in it...
             }
?>

任何帮助,建议表示赞赏&lt; 3谢谢!

1 个答案:

答案 0 :(得分:1)

如果您希望它能够正常运行,则必须包含通配符。因此,如果您要在字符串中查找该字词,您可以执行以下操作...

$query .= "title LIKE '%".$each."%'";

百分比(%)将与任何内容(任何类型的零个或多个字符)匹配。