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

Php 用于查询目的的精确字符串匹配,php,sql,Php,Sql,我试图查询某个字符串/单词,并查询一组与之相关的结果,但SQL语句有问题。 例如:当我尝试用当前代码搜索属性_代码“TA001”时,它将查询回TA001、CTA001、JTA001等。我只需要准确提交的结果 我尝试过用=替换LIKE函数,并删除了通配符%,但没有返回任何结果。任何帮助都将不胜感激。代码如下: <?php error_reporting(E_ALL); ini_set('display_errors', '1'); $search_output = ""; if(isset

我试图查询某个字符串/单词,并查询一组与之相关的结果,但SQL语句有问题。
例如:当我尝试用当前代码搜索属性_代码“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";
}
}
?>
这行中的

   $sqlCommand = "(SELECT id, property_code, street, street2, city, state, zip FROM properties WHERE property_code LIKE '% $searchquery %')";
您在“%1”和$searchquery之间有一个类似条件的空格-这是问题之一

如果只想搜索以$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}'";
} 

如果您想要精确,为什么要使用LIKE和通配符%n您是对的,它应该是:WHERE property_code=“$searchquery”…您确定有一行包含该信息吗?此外,在回显结果时,您还需要确保小心XSS。用
=
(等)替换
查询正是我的建议。您应该查看该列中的值,以查看是否有空格或其他意外字符导致精确匹配失败。另外,您应该使用preparedstatements(PDO)来防止SQL注入。谢谢大家。我会调查所有这些tomm,看看我能找到什么有用的