您需要通過在$dbh
中創建一個新的PDO對象來實際建立與數據庫的連接。下面的代碼假定數據庫用戶和密碼爲$dbusername, $dbpassword
,數據庫的名稱爲$nameofdb
。
$date_added
在prepare()
調用中被替換爲參數:dateadded
,然後通過數組傳遞給調用。
請仔細閱讀這兩個PDO::__construct()
和PDO::execute()
<?php
require_once('globals.php');
// Connect to MySQL via PDO
try {
$dbh = new PDO("mysql:dbname=$nameofdb;host=localhost", $dbusername, $dbpassword);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
$date_added = $_POST['date_added'];
// Replace `$date_added` with a parameter `:dateadded`
$sth = $dbh->prepare("SELECT * FROM games WHERE date_added > :dateadded");
// bind $date_added and pass it into the execute() call inside an array
$sth->execute(array('dateadded'=>$date_added));
/* Fetch all of the remaining rows in the result set */
print("Fetch all of the remaining rows in the result set:\n");
$result = $sth->fetchAll();
print_r($result);
?>
的文檔是否行得通?如果不是:你看到的錯誤是什麼?這裏的一個問題是,你直接在查詢中使用用戶數據 - 使用預準備語句或$ dbh-> quote() – johannes
這裏是錯誤:致命錯誤:調用非對象的成員函數prepare()。 –
這不是公共形式。 –