2014-02-07 46 views
-1

我使用:擴展準備()到數據庫級

> $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

@ Nouphal.M編輯包括我的數據庫類。 – ncf

+0

爲什麼你覺得**你需要一個「數據庫類」? –

+0

@teresko我想我不需要它爲我在做什麼。我只是建立了一個單獨的函數來返回鏈接連接,並且它在prepare和execute方法中工作正常。 – ncf

回答

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); 
     } 
} 
+0

我試着做這個改變,但仍然出現錯誤。 – ncf

+0

這會殺死封裝並消除數據庫類的必要性。 –

+0

你現在得到什麼錯誤? –

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."); 
    } 

} 

然後就可以調用$分貝,就好像它是一個mysqli對象

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

但是你應該直接使用mysqli對象,如果你真的沒有增加任何功能的類...

+0

他在每種方法中都添加了mysql錯誤管理('OR die ...'),我希望它能夠減少代碼重複。這是一個很好的決定,但我會拋出異常而不是'OR die'聲明。 –

+1

@Tomás在這種情況下,他應該使用更多更新的'PDO'類,它實際上會拋出異常,包含'mysqli'的所有功能,並且在功能上稍微更先進。 – Populus