2016-07-21 42 views
1

我需要一個幫助。我無法從數據庫中搜索出使用PHP和MySQL關鍵詞的值。我在下面解釋我的代碼。無法在PHP和MySQL中使用關鍵字進行正確搜索

$searchKey=$_GET['searchKey']; 
$special_id=$_GET['special_id']; 
$city_id=$_GET['city_id']; 
$day_id=$_GET['day_id']; 
$keyword = '%'.$searchKey.'%'; 
$data=array(); 
$sql =mysqli_query($connect,"SELECT * FROM db_restaurant_basic WHERE rest_name LIKE '".$keyword."' and special='".$special_id."' and city='".$city_id."' and status=1 GROUP BY member_id ORDER BY member_id DESC "); 
if(mysqli_num_rows($sql) > 0){ 
    while($row=mysqli_fetch_array($sql)){ 
     $data[]=array("restaurant_name"=>$row['rest_name']); 
    } 
} 
$result=array("data"=>$data); 
echo json_encode($result); 

當我調用以下URL來獲得結果。

http://localhost/spesh/mobileapi/categoryproduct.php?item=2&acn=5&special_id=1&city_id=1&day_id=4&searchKey=on 

它給了我以下結果。

{"data"[{ 
    "restaurant_name":"Sonoma on 9th" 
},{ 
    "restaurant_name":"Jamesons Irish Pub 17th Ave. SW" 
},{ 
    "restaurant_name":"Jamesons Irish Pub Brentwood NW" 
},{ 
    "restaurant_name":"National on 17th" 
} 
] 
} 

這裏我的問題是,我需要搜索包含關鍵字onRestaurant name但在這裏我得到了一些其他Restaurant name不包含關鍵字on。這裏其實我需要的時候用戶將使用搜索餐館名稱關鍵字on它應該給包含該詞的餐廳名稱on只有其他餐廳的名稱。請幫助我。

回答

3

您在查詢中使用關鍵字「like」,該關鍵字在餐廳名稱中隨處搜索「on」。

你應該使用的空間,使之具體

$keyword = '% '.$searchKey.' %'; 

檢查第一個%符號後的空間和之前第二個

+0

它工作了,謝謝。 – satya

+0

非常歡迎,謝謝 –

2

添加空格的關鍵字各地:

$keyword = '% '.$searchKey.' %'; 

順便說一句:瞭解緊靠準備語句以防止SQL注入。

+0

運氣不好。你先回答,但OP仍然選擇另一個。 Upvoted你。 –

+0

@LoganWayne不應接受第一個答案。最好的答案應該被接受,也許另一個更好。 – Jens

+0

看起來和我一樣 –

0

而是採用直接替換值,可以使用下面的方法來避免SQL注射。

你基本上有兩種選擇來實現這一目標:

參考docs

例如,使用庫MySQLi(MySQL的):

$stmt = $dbConnection->prepare('SELECT * FROM employees WHERE name = ?'); 
$stmt->bind_param('s', $name); 

$stmt->execute(); 

$result = $stmt->get_result(); 
while ($row = $result->fetch_assoc()) { 
    // do something with $row 
} 

請參閱如何I prevent SQL-injection in PHP