面向对象的搜索功能PHP

时间:2012-11-04 14:02:48

标签: php search mysqli

您好我正在尝试使用OOP PHP创建搜索功能但是当我运行查询并输入错误数据时,我仍然会得到结果。数据库中没有的结果。

我觉得我的代码中缺少某些东西,

也许我的查询错了我不确定因为我是整个编程方面的新手。

欢迎任何帮助!

的index.php

  <?php
 include("classes/class.House.inc"); 
 ?>
 <!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>
 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
 <title>UndergradPad</title>
 <link rel="stylesheet" type="text/css" href="css/style.css" />

 </head>
 <body>
 <div id="bodyWrapper">
 <div id"header">
 <img id="banner" alt="UnderGradPad Logo" src="images/banner.png"/>
 </div> <!-- End header -->

 <div id="search">
<h1>Find student accomodation</h1><br/>
<p> Location  </p>
    <form method="post" action="search.php" name="search" id="searchform">
    <input type="text" name="term" id="searchinput"/>
    <input type="submit" name="submit" id="searchsubmit" value=""/>
    </form>
 <div class="help">e.g. 'PO5' or 'Portsmouth'</div>
 </div> <!--End search -->
 </body>
 </html>

类/ class.House.inc

  <?php 
     include("connect/class.Database.inc");

    class House extends Database {

     public function search (){

        $query = "SELECT * FROM houses WHERE postcode like '%$term%'";

                $result = $this->mysqli->query($query);

                $num_result = $result->num_rows;    
                if($num_result > 0){
                    while($rows =$result->fetch_assoc()){               
                        $this->data[]=$rows;
                        //print_r($rows);
                    }           
                    return $this->data;
            } 
    } else {
        echo 'No Records Found';    
        }
             } }
 ?>

1 个答案:

答案 0 :(得分:1)

首先,未定义$term变量。

你可能意味着$_POST['term']?这是PHP为发布数据定义的全局变量。

但是,我建议将变量作为函数的参数,因为它可以让您灵活地使用它而不依赖于帖子数据。

例如:

function Search($term) {
    // now you can use $term as a local variable within the function.
}

...并在您调用它的代码中,将$_POST['term']作为参数传递。使用这样的东西:

$houseobject->Search($_POST['term']);

其次,您需要转义SQL数据,否则您将面临SQL注入的风险。由于您使用MySQLi类进行数据库访问,因此这里有两种方法:自己转义变量,或使用参数化查询让MySQLi为您完成工作。

  • 自己逃避:

    $query = "SELECT * FROM houses WHERE postcode like '%".$this->mysqli->real_escape_string($term)."%'";
    $result = $this->mysqli->query($query);
    
  • 参数化查询:

    $query = "SELECT * FROM houses WHERE postcode like ?";  // ? placeholder in query
    $stmt = $this->mysqli->prepare($query);
    $stmt->bind_param("s", "%$term%");       // insert your variable into the placeholder (still need to add % wildcards)
    $stmt->execute();
    

    有关预准备陈述的更多信息,请参阅the PHP manual

参数化查询被认为是更安全和更现代的方法,但无论哪种方式都可以正常工作。你必须做一个或另一个;没有它们,只要有人在代码中输入引号,你的程序就会中断,并且可以很容易地用来破解网站。

最后一点:在字符串两端使用%在SQL中进行通配符搜索非常慢。如果DB很小,你会没事的,但随着它的增长,查询会越来越慢。如果您希望表中有超过几百条记录,则应认真考虑其他搜索方法。 (这里有很多选择,取决于你的需求,所以我现在不再讨论它们,而是做一些研究,看看什么对你最好)。

希望有所帮助。

相关问题