2012-04-11 82 views
0

我想查詢某個字符串/字,並查詢一堆與它有關的結果,但是與SQL語句有關。
例如:當我嘗試用當前代碼搜索property_code「TA001」時,它將回詢TA001,CTA001,JTA001等。我只想要確切的提交結果。用於查詢的精確字符串匹配

我試着用=來代替LIKE函數,並且還刪除了通配符%,但不會返回任何結果。任何幫助,將不勝感激。這裏是代碼:

<?php 

error_reporting(E_ALL); 
ini_set('display_errors', '1'); 
$search_output = ""; 
if(isset($_POST['searchquery']) && $_POST['searchquery'] != ""){ 
$searchquery = preg_replace('#[^a-z 0-9]-#i', '', trim(strtoupper($_POST['searchquery']))); 
if($_POST['filter1'] == "properties"){ 
    $sqlCommand = "(SELECT id, property_code, street, street2, city, state, zip FROM properties WHERE property_code LIKE '% $searchquery %')"; 
} else if($_POST['filter1'] == "vendor"){ 
    $sqlCommand = "SELECT id, vendor_name FROM vendor WHERE vendor_name LIKE '%$searchquery%'"; 
} 
    include_once("database.php"); 
    $query = mysql_query($sqlCommand) or die(mysql_error()); 
$count = mysql_num_rows($query); 
if($count > 1){ 
    $search_output .= "<hr />$count results for <strong>$searchquery</strong><hr />$sqlCommand<hr />"; 
    while($row = mysql_fetch_array($query)){ 
     $id = $row["id"]; 
     $property_code = $row["property_code"]; 
     $street = $row["street"]; 
     $street2 = $row["street2"]; 
     $city = $row["city"]; 
     $state = $row["state"]; 
     $zip = $row["zip"]; 
     $search_output .= "Item ID: $id: - $property_code, $street, $street2, $city, $state $zip<br />"; 
      } // close while 
} else { 
    $search_output = "<hr />0 results for <strong>$searchquery</strong><hr />$sqlCommand"; 
} 
} 
?> 
+1

,你爲什麼使用LIKE和通配符% – 2012-04-11 20:46:42

+0

你是對的,它應該是:WHERE property_code ='$ searchquery'..你確定你有這行信息嗎?在迴應結果時,您還需要確保您對XSS保持謹慎。 – tcole 2012-04-11 20:47:09

+0

用'='替換LIKE'查詢(等等)正是我所建議的。您應該查看該列中的值,看看是否有空格或其他意外字符導致精確匹配失敗。另外,您應該使用預準備語句(PDO)來防止SQL注入。 – 2012-04-11 20:47:29

回答

1

在這一行:

$sqlCommand = "(SELECT id, property_code, street, street2, city, state, zip FROM properties WHERE property_code LIKE '% $searchquery %')"; 

你已經得到%和$ SEARCHQUERY之間」在LIKE條件的空間 - 這是問題的一個。

,如果你只想搜索開始$ SEARCHQUERY字符串的記錄也許嘗試這樣的:

if($_POST['filter1'] == "properties"){ 
$sqlCommand = "SELECT id, property_code, street, street2, city, state, zip FROM properties WHERE property_code LIKE '{$searchquery}%'"; 
} else if($_POST['filter1'] == "vendor"){ 
    $sqlCommand = "SELECT id, vendor_name FROM vendor WHERE vendor_name LIKE '{$searchquery}%'"; 
} 

如果你想精確匹配試試這個:

如果你想確切
if($_POST['filter1'] == "properties"){ 
    $sqlCommand = "SELECT id, property_code, street, street2, city, state, zip FROM properties WHERE property_code = '{ $searchquery'"; 
} else if($_POST['filter1'] == "vendor"){ 
    $sqlCommand = "SELECT id, vendor_name FROM vendor WHERE vendor_name = '{$searchquery}'"; 
} 
+0

謝謝你們。我會研究這個tomm,看看我能找到那個作品 – sammich 2012-04-11 22:06:47