php - mysql 搜索返回整个表

标签 php mysql search

我正在使用这个 PHP 来执行搜索,但它返回表中的所有内容,而不是与搜索相关的任何内容...我还收到“mysqli_real_escape_string”错误,但我不确定它是否相关。

<?php
$con=mysqli_connect("***","***","***","***");
// Check connection
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }
?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Search results</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <link rel="stylesheet" type="text/css" href="style.css"/>
</head>
<body>
<?php
    $query = $_GET['query']; 
    // gets value sent over search form

    $min_length = 3;
    // you can set minimum length of the query if you want

    if(strlen($query) >= $min_length){ // if query length is more or equal minimum length then

        $query = htmlspecialchars($query); 
        // changes characters used in html to their equivalents, for example: < to &gt;

        $query = mysqli_real_escape_string($query);
        // makes sure nobody uses SQL injection

        $raw_results = mysqli_query($con,"SELECT * FROM test_table
            WHERE ('email' LIKE '%".$query."%') OR ('pw' LIKE '%".$query."%')") or die(mysqli_error());

        if(mysqli_num_rows($raw_results) > 0){ // if one or more rows are returned do following

            echo "<table border='1'>
            <tr>
            <th>email</th>
            <th>pw</th>
            </tr>";

            while($results = mysqli_fetch_array($raw_results)){
            // $results = mysql_fetch_array($raw_results) puts data from database into array, while it's valid it does the loop

                echo "<tr><td>".$results['email']."</td><td>".$results['pw']."</td></tr>";
                //echo "<p><h3>".$results['email']."</h3>".$results['pw']."<br/>".$results['ID']."</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;
    }
?>
</body>
</html>

最佳答案

您的查询不正确。您应该使用反引号,而不是引号

$raw_results = mysqli_query($con,"SELECT * FROM test_table
        WHERE (`email` LIKE '%".$query."%') OR (`pw` LIKE '%".$query."%')") or
die(mysqli_error());

此外,mysqli_real_escape_string 要求第一个参数为 $con

$query = mysqli_real_escape_string($con, $query);

关于php - mysql 搜索返回整个表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16783683/

相关文章:

php - 查找多维数组中的重复值

php - Codeigniter - 如何运行多个/批量查询?

php - mysqli - 如何在 0 个受影响的行上返回 false

php - 无法从 MySQL 获取结果访问 JSON 对象,PHP

php/laravel - 如何根据最大数字排列数组并对其进行编号

php - 在 PHP/MYSQL 中查找最近的邮政编码位置

php - 将可变文本嵌入到 php/html 网页中

两张表之间的MySQL更新查询

laravel - 如何在我的索引中搜索拼写错误的单词?

.htaccess - 我怎样才能排除不再在我的站点地图中的页面被谷歌索引?