从DB php搜索数据

时间:2017-09-28 13:14:52

标签: php mysql oop mysqli

我在home.php中有搜索框

<form action ="search.php" method = "post">

<input name="search" type="text" size="30" placeholder="...."/>

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

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

和serach.php文件

<?php
require_once("class.user.php");
require_once("class.db.php");
$output = '';

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

$connection = new DB_con();

$query = $mysqli->query("SELECT * FROM users WHERE username LIKE '%".$search."%' AND email LIKE '%".$search."%'") or die ("Could not search");
$result =$mysqli->query($connection, $query);
$count = $result->num_rows;

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

}else{

  while ($row = $result->fetch_array($query)) {

    $username = $row ['username'];
    $email = $row ['email'];


    $output .=$username.''.$email;

  }

}
}
?>

我有几个错误。 注意:未定义的变量:第12行的search.php中的mysqli

  

致命错误:未捕获错误:在null上调用成员函数query()   在\ search.php:12堆栈跟踪:#0 {main}在search.php上投放   12

1 个答案:

答案 0 :(得分:2)

$mysqli未定义,因此您收到错误,并且您正在进行两次查询。

<?php
require_once("class.user.php");
require_once("class.db.php");
$output = '';

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

    $connection = new DB_con();

    $query = "SELECT * FROM users WHERE username LIKE '%" . $search . "%' AND email LIKE '%" . $search . "%'";
    if ($result = $connection->query($query)) {
        if ($result->num_rows > 0) {
            while ($row = $result->fetch_assoc($query)) {

                $username = $row['username'];
                $email    = $row['email'];


                $output .= $username . '' . $email;

            }
        } else {

            $output = "There was no search results!";
        }


    } else {

        printf("Errormessage: %s\n", $connection->error);
    }

}
?>