php查询搜索不稳定的结果

时间:2018-05-04 05:35:04

标签: php mysql search

我想创建一个搜索栏来查询我的MySql Db。

<?php
$query = $_POST['search_name']; 

$min_length = 3;

if(strlen($query) >= $min_length){ 
    $query = mysqli_real_escape_string($connection,$query);
    $raw_results = mysqli_query($connection, "SELECT * FROM `companies`
        WHERE (`name` LIKE '%$query%')");

    if(mysqli_fetch_row($raw_results) > 0){ 
        while($results = mysqli_fetch_row($raw_results)){

            echo "<p>".$results[0]." ".$results[1]."</p>";

        }

    }
    else{ // if there is no matching rows do following
        echo "No results";
    }

}
else{ // if query length is less than minimum
    echo "Minimum length is ".$min_length;
}
?>

现在,如果我在栏中输入 gaio ,我就不会得到结果Gaiotto Automation。令人惊讶的是,如果我直接在SQL终端中输入查询

 SELECT * FROM `companies` WHERE (`name` LIKE '%gaio%')

然后结果是Gaiotto Automation,这就是我想要的。如果我在搜索栏中输入autom,那么我会在结果中获得Gaiotto Automation

3 个答案:

答案 0 :(得分:1)

在你的sql代码中使用php var时要小心你有sqlinjection风险

为了避免这种情况,你应该检查你的db驱动程序是否有绑定参数

无论如何你应该以适当的方式构建查询串行模式,例如:uisng concat

  $raw_results = mysqli_query($connection, "SELECT * FROM `companies`
        WHERE (`name` LIKE concat('%', '$query', '%') )");

答案 1 :(得分:0)

我怀疑你的参数没有被修剪,但无论如何我建议你使用预备语句

http://php.net/manual/en/mysqli.quickstart.prepared-statements.php

您知道您的sql语法直接工作,因此您可以通过回显帖子页面上的sql语句进行调试。

答案 2 :(得分:-1)

您必须在mysqli_num_rows中使用mysqli_fetch_row代替if condition,因为它已经在条件中提取了结果,因此下次无法工作。

<?php
$query = $_POST['search_name']; 

$min_length = 3;

if(strlen($query) >= $min_length){ 
    $query = mysqli_real_escape_string($connection,$query);
    $raw_results = mysqli_query($connection, "SELECT * FROM `companies` WHERE (`name` LIKE '%$query%')");

    if(mysqli_num_rows($raw_results) > 0){ 
        while($results = mysqli_fetch_row($raw_results)){

            echo "<p>".$results[0]." ".$results[1]."</p>";

        }

    }
    else{ // if there is no matching rows do following
        echo "No results";
    }

}
else{ // if query length is less than minimum
    echo "Minimum length is ".$min_length;
}
?>