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";
}
}
?>
4

1 回答 1

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}'";
} 
于 2012-04-11T21:14:14.920 回答