PHP搜索栏无法正常工作

时间:2018-04-02 21:05:44

标签: php

我试图创建一个搜索标题的搜索栏..数据库正在运行,内容显示在搜索栏下,然后我搜索某事,它显示我"连接成功然后没有结果..什么&# 39;错了吗?

<?php 
include 'header.php';
?>

<h3>Rezultate</h3>
<div class"article-container">
<?php 

  if ($conn->connect_error) 
  {
   die("Connection failed: " . $conn->connect_error);
  }
   else 
  echo "Connected successfully";

        if(isset($_POST['submit-search']))
        {

            $search = mysqli_real_escape_string($conn, $_POST['search']);
            $sql = "SELECT * FROM article WHERE a_title LIKE '%search%'";
            $result = mysqli_query($conn, $sql);
          $queryResult = mysqli_num_rows($result);

        if($queryResult >0)
        {
           while ($row = mysqli_fetch_assoc($result))
                echo"<div>
                        <h3>".$row['a_title']."</h3>
                        <p>".$row['a_text']."</p>
                        <p>".$row['a_author']."</p>
                        <p>".$row['a_dat']."</p>
                     </div>";
        }
            else 
            {
                echo "<br>No result!";
            }
        }
?>
</div>

2 个答案:

答案 0 :(得分:2)

在SQL查询中引用变量$search时,您的SQL是错误的。只需将%search%更改为%$search%

即可
$search = mysqli_real_escape_string($conn, $_POST['search']);
$sql = "SELECT * FROM article WHERE a_title LIKE '%$search%'";

另外,我坚信您应该考虑将准备好的语句用于任何涉及用户输入的内容。

$search = "%" . $_POST['search'] . "%";
$sql = "SELECT * FROM article WHERE a_title LIKE ?";
if($stmt = $mysqli_prepare($conn, $sql)) {
    /* bind parameters for markers */
    mysqli_stmt_bind_param($stmt, "s", $search);

    /* execute query */
    mysqli_stmt_execute($stmt);

    /* bind result variables */
    mysqli_stmt_bind_result($stmt, $district);

    /* fetch value */
    mysqli_stmt_fetch($stmt);

    printf("%s Search Result: %s\n", $search);

    /* close statement */
    mysqli_stmt_close($stmt);
}

这将为您提供更多针对SQL注入的保护。

答案 1 :(得分:0)

$sql = "SELECT * FROM article WHERE a_title LIKE '%search%'";

您当前的查询正在搜索字符串&#34;搜索&#34;等字词。修复它以使其成为PHP变量。

$sql = "SELECT * FROM article WHERE a_title LIKE '%$search%'";