我對PDO很陌生,也是一般的PHP的OOP,所以請大家好:)基本上我試圖建立一個基於PDO的連接對象,這樣我就可以在我的網站中調用一個連接。製作PDO mysql靜態連接類的最佳方法?
我需要一些準備好的語句,根據我通過使用下面要創建的同一個數據庫對象的標識查找不同的結果。
如何製作和訪問我在下面設置的db類,然後使用它中的函數來提取我需要的相關信息?任何例子都很棒,所以我可以瞭解最佳實踐等。
非常感謝提前。
class db {
private static $connection;
private function __construct(){}
private function __clone(){}
private static function connect($db_server="localhost", $db_user="user", $db_pass="password") {
if(!$this->connection){
try{
$this->connection = new PDO($db_server, $db_user, $db_pass);
} catch (PDOException $e) {
$this->connection = null;
die($e->getMessage());
}
}
return $this->connection;
}
}
$dbh = new db::connect();
$stmt = $dbh->prepare("SELECT * FROM questions where id = ?");
if($stmt->execute(array($_REQUEST['testid']))) {
while ($row = $stmt->fetch()) {
print_r($row);
}
}
僞變量$這在靜態方法和靜態屬性中不可用。你應該使用self :: $屬性。否則,它會說屬性db :: property not defined – jscripter 2016-03-18 15:25:01
@BubuDaba不會在問題中編輯不正確的代碼,因爲它可以使其他asnwers不相關。如果你對OP有一個建議,那麼寫一個答案或一個評論 – 2016-03-18 16:21:42