我想查询某个字符串/字,并查询一堆与它有关的结果,但是与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";
}
}
?>
,你为什么使用LIKE和通配符% – 2012-04-11 20:46:42
你是对的,它应该是:WHERE property_code ='$ searchquery'..你确定你有这行信息吗?在回应结果时,您还需要确保您对XSS保持谨慎。 – tcole 2012-04-11 20:47:09
用'='替换LIKE'查询(等等)正是我所建议的。您应该查看该列中的值,看看是否有空格或其他意外字符导致精确匹配失败。另外,您应该使用预准备语句(PDO)来防止SQL注入。 – 2012-04-11 20:47:29