我使用:擴展準備()到數據庫級
> $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.");
}
}
@ Nouphal.M編輯包括我的數據庫類。 – ncf
爲什麼你覺得**你需要一個「數據庫類」? –
@teresko我想我不需要它爲我在做什麼。我只是建立了一個單獨的函數來返回鏈接連接,並且它在prepare和execute方法中工作正常。 – ncf