Mysqli-通用数据库类,函数文件...如何使用准备好的语句?

时间:2019-01-19 00:11:36

标签: php mysql

我有一个大约一年前建立的站点,并使用mysqli_real_escape_string保护输入。 现在,我想“升级”准备好的语句的安全性,但是我做事的方式遇到了问题。我没有考虑更改所有内容,但是在这里看不到如何应用准备好的语句。

我有一个与此相关的数据库类:

<?php

  class Database {

    private $cnx;
    private $hostname;
    private $user;
    private $password;
    private $database;

    public function __construct($hostname, $database, $user, $password) {
      $this->hostname = $hostname;
      $this->user = $user;
      $this->password = $password;
      $this->database = $database;

      //create connection
      $this->cnx = new mysqli($this->hostname, $this->database, $this->user, $this->password);
      //check for errors in the connection
      if($this->cnx->connect_error) {
        die($this->cnx->connect_error);
      }
      //encode de characters
      $this->cnx->set_charset('utf8');
    }

    //check for errors in the query
    public function checkError() {
        if($this->cnx->error) {
          die($this->cnx->error);
        }
    }


    //query to DB
    public function query($sql) {
      $this->cnx->prepare($sql);
      $this->checkError();
    }


    //query with several records result
    public function getRows($sql) {
      $query = $this->cnx->query($sql);
      $this->checkError();
      $items = array();
      while($row = $query->fetch_object()) {
        $items[] = $row;
      }
      return $items;
    }


    //just one result
    public function get_single_row($sql) {
      $query = $this->cnx->query($sql);
      $this->checkError();
      $item = $query->fetch_object();
      return $item;
    }

    //Escape string
    public function escape($string){
        return $this->cnx->real_escape_string($string);
    }

  }

然后我有一个分隔的函数文件,例如,此函数:

 public function deleteAd($id, $status) {
      $this->db->query("UPDATE adverts SET ad_deleted='$status' WHERE ad_id='$id'");
    }

  public function getDetail($id) {
      return $this->db->get_single_row("SELECT * FROM adverts WHERE ad_id='$id'");
    }

最后,我进入了我要查询的页面。例如:

//get ad detail for selected id
if(isset($_GET['id'])) {
    $id = $db->escape($_GET['id']);
    $ad = $adverts->getDetail($id);
}

/*delete ad*/
if(isset($_GET['id'])) {
    $id = $db->escape($_GET['id']);
    $delete = $db->escape($_GET['delete']);
    $adverts->deleteAd($id, $delete);
    header('location:adverts.php');
    $adverts->getAll();
}

所以,我知道我必须做这样的事情:

$stmt = $db->prepare("UPDATE adverts SET ad_deleted=? WHERE ad_id=?");
$stmt = bind_param("ii", $delete, $id);
$stmt = execute

但是,如果我尝试这样做:

 public function deleteAd($id, $status) {
      $this->db->prepare(query("UPDATE adverts SET ad_deleted='$status' WHERE ad_id='$id'"));
    }

我得到一个错误。 我可以使用通过这种结构准备的语句,还是必须重做所有内容?

0 个答案:

没有答案