Php 将prepare()扩展到数据库类

Php 将prepare()扩展到数据库类,php,oop,Php,Oop,我正在使用: > $db = new Database(); // my own Database class > $result = $db -> query(sql); > $row = $result -> fetch_array(MYSQLI_BOTH); 。。。它做得很好,没有任何问题。但是,通常情况下,sql会根据用户输入(或者可以通过用户输入进行更改)进行一些更改,我了解到,这种更改非常容易受到sql注入的影响。哎呀 因此,我一直在阅读准备好的声

我正在使用:

> $db = new Database(); // my own Database class

> $result = $db -> query(sql);

> $row = $result -> fetch_array(MYSQLI_BOTH);
。。。它做得很好,没有任何问题。但是,通常情况下,sql会根据用户输入(或者可以通过用户输入进行更改)进行一些更改,我了解到,这种更改非常容易受到sql注入的影响。哎呀

因此,我一直在阅读准备好的声明,我准备切换到更像这样的内容:

> $db = new Database();

> $stmt = $db -> prepare(sql);

> if ($stmt->execute(array($_GET['name'])) {

> > while ($row = $stmt->fetch()) {

> > > print_r($row);

> > }

> }
。。。这是我从他那里抢来的。我已经修改了我的代码以满足我的需要,但是我得到了对未定义方法Database::prepare()的调用,我意识到这意味着我在类中没有可用的prepare()方法。如何扩展此功能?如果你不介意的话,一点解释可能会有帮助

编辑:以下是我当前数据库类的内容

class Database {

private $link;
private $host = "#####";
private $username = "#####";
private $password = "####";
private $db = "####";

public function __construct(){
    $this->link = new mysqli($this->host, $this->username, $this->password, $this->db)
        OR die("There was a problem connecting to the database.");
    return true;
}

public function query($query) {
    $result = mysqli_query($this->link, $query);
    if (!$result) die('Invalid query: ' . mysql_error());
    return $result;
}

public function __destruct() {
    mysqli_close($this->link)
        OR die("There was a problem disconnecting from the database.");
}

}

从构造中返回mysqli链接,或者可以编写一个get方法来返回链接

public function __construct(){
    $this->link = new mysqli($this->host, $this->username, $this->password, $this->db)
        OR die("There was a problem connecting to the database.");
    return $this->link;
}
试试这个:

 $db = new Database();
 $name = $_GET['name']; // try validating the user input here
 if( $stmt = $db->prepare($sql) ){
       $stmt->bind_param("s", $name);
       $stmt->execute();
       while ($row = $stmt->fetch()) {
           print_r($row);
       }
 }

创建
数据库
扩展
mysqli

class Database extends mysqli
{

    private $link;
    private $host = "#####";
    private $username = "#####";
    private $password = "####";
    private $db = "####";

    public function __construct()
    {
        parent::__construct($this->host, $this->username, $this->password, $this->db)
        OR die("There was a problem connecting to the database.");
    }

    public function __destruct()
    {
        mysqli_close($this->link)
        OR die("There was a problem disconnecting from the database.");
    }

}
然后您可以调用$db,就好像它是
mysqli
对象一样

$db = new Database();
$db->query($sql);

但是如果你不是真的在类中添加任何功能,你应该直接使用
mysqli
对象…

@Nouphal.M编辑以包含我的数据库类。为什么你认为你需要一个“数据库类”?@teresko我想我做的事情不需要它。我刚刚构建了一个单独的函数,用于返回链接连接,它与prepare和execute方法配合得很好。我尝试进行此更改,但仍然出现错误。这将终止封装并消除数据库类的必要性。他正在添加mysql错误管理(
或die…
)在每种方法中,我都希望它能减少代码重复。这是一个很好的决定,但我会抛出异常,而不是
或die
语句。@Tomás在这种情况下,他应该使用更新得多的
PDO
类,它实际上抛出异常,包括
mysqli
的所有功能,并且在功能上稍微高级一些。