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


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

我想创建一个表单,允许用户键入搜索,并让它从数据库中提取正确的值并显示它们,由于某些原因,我无法让我的查询工作,它只显示"无法搜索"

这是我的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(mysqli_error($connection))来捕获任何错误(如果有的话),而不是or die ("Could not search")

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

<?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)); 

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

  • http://php.net/manual/en/function.mysqli-connect.php
$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中声明的用于连接到数据库的变量。

你应该把$result放在$count之前。

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

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