用于查询目的的精确字符串匹配

时间:2012-04-11 20:43:14

标签: php sql

我正在尝试查询某个字符串/单词并查询一堆与之相关的结果,但是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 个答案:

答案 0 :(得分: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}'";
}