2017-03-03 59 views
1

我創建了一個簡單的搜索引擎來顯示來自數據庫的結果,但我需要它顯示所有帶有類似字符的結果,而不是整個確切的單詞。所以,例如用戶類型eng--它應該返回結果引擎和所有其他單詞與eng,但目前它只會返回一些東西,當你輸入整個單詞,engine.Guess我有一個錯誤的地方,但無法真正找到它:有我的代碼。SQL「LIKE」選擇器在我的搜索引擎中像「=」一樣工作

<?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... 
      } 
?> 

任何幫助,建議表示讚賞< 3謝謝!

回答

1

LIKE必須包含通配符,如果您希望它行爲正常。所以,如果你正在尋找的字符串中的字,你可以做這樣的事情...

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

的百分比(%)將匹配任何東西(任何種類的零個或多個字符)。

+0

哇我知道這是一件容易的事,但不知道這是與任何事情匹配的標誌,謝謝你正是我所需要的<3將在7分鐘內接受 –

+0

還有一些其他選項,但百分比意味着零或更多的字符,所以它會在字符串的開頭或結尾找到單詞。這裏有更多... https://www.w3schools.com/SQl/sql_wildcards.asp –

+0

謝謝你的信息! –