我正在使用:
> $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);
> > }
> }
...我从example #3抓住了。我已经改变了我的代码以适合我想要的但是我得到了Call to undefined method 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.");
}
}
答案 0 :(得分:0)
从构造中返回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);
}
}
答案 1 :(得分:0)
让Database
延长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
对象......