如何使用 PHP、mysqli 和 html 表单创建搜索

How to create a search using PHP, mysqli and a html form

我想创建一个表单,允许用户输入搜索并让它从数据库中获取正确的值并显示它们,出于某种原因我无法让我的查询工作它只是显示"could not search"

这是我的 php 代码

 <?php

  include "connect.php";

  $output = '';

  if(isset($_POST['search'])) {
    $search = $_POST['search'];
    $search = preg_replace("#[^0-9a-z]i#","", $search);

    $query = mysqli_query("SELECT * FROM house WHERE town LIKE '%$search%'") or die ("Could not search");
    $count = mysqli_num_rows($query);
    
    if($count == 0){
      $output = "There was no search results!";

    }else{

      while ($row = mysqli_fetch_array($query)) {

        $town = $row ['town'];
        $street = $row ['street'];
        $bedrooms = $row ['bedrooms'];
        $bathroom = $row ['bathrooms'];

        $output .='<div> '.$town.''.$street.''.$bedrooms.''.$bathrooms.'</div>';

      }

    }
  }

  ?>

这是我的表格

 <form action ="home.php" method = "post">
  
          <input name="search" type="text" size="30" placeholder="Belfast"/>

          <input type="submit" value="Search"/>

          </form> 

          <?php print ("$output");?>

您没有在查询中连接到您的数据库:

$query = mysqli_query("SELECT
                      ^ missing connection variable

没有连接变量(不知道你用什么连接)

$query = mysqli_query($connection, "SELECT ...
                      ^^^^^^^^^^^^

来自手册http://php.net/manual/en/mysqli.query.php

面向对象风格 mixed mysqli::query ( string $query [, int $resultmode = MYSQLI_STORE_RESULT ] )

程序风格 mixed mysqli_query ( mysqli $link , string $query [, int $resultmode = MYSQLI_STORE_RESULT ] )

假设您正在使用 mysqli_ 进行连接。如果您使用 mysql_ 或 PDO 进行连接,那将不起作用。这些不同的 MySQL API 不会相互混合。

另外,or die ("Could not search")or die(mysqli_error($connection)) 来捕捉任何错误,如果有的话。

error reporting 添加到文件顶部,这将有助于查找错误。

<?php 
error_reporting(E_ALL);
ini_set('display_errors', 1);

// rest of your code

旁注:错误报告只应在试运行中进行,绝不能在生产中进行。


示例 mysqli 连接:

$connection = mysqli_connect("myhost","myuser","mypassw","mybd") 
                or die("Error " . mysqli_error($connection)); 

欲了解更多信息,请访问:

$query = mysqli_query("SELECT * FROM house WHERE town LIKE '%$search%'") or die ("Could not search");

$result = mysqli_query($connection,$query);

$count = mysqli_num_rows($result);

$connection 是在您的 connect.php 中声明的变量,用于连接到您的数据库。

你应该在 $count 之前输出 $result

尝试删除 if($count==0) 之间的 space 它将开始工作!!

if($count==0){
      $output = "There was no search results!";}