2011-10-26 88 views
0

我想從另一個頁面傳遞變量並將其用於PDO查詢。該變量是記錄添加的日期,我試圖返回所有新記錄。我是否在PDO中使用$ _POST?在使用PDO的查詢中使用傳遞的變量

<?php 
require_once('globals.php'); 

$date_added = $_POST['date_added']; 

$sth = $dbh->prepare("SELECT * FROM games WHERE date_added > $date_added"); 
$sth->execute(); 

/* 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); 


?> 
+1

的文檔是否行得通?如果不是:你看到的錯誤是什麼?這裏的一個問題是,你直接在查詢中使用用戶數據 - 使用預準備語句或$ dbh-> quote() – johannes

+0

這裏是錯誤:致命錯誤:調用非對象的成員函數prepare()。 –

+0

這不是公共形式。 –

回答

2

您需要通過在$dbh中創建一個新的PDO對象來實際建立與數據庫的連接。下面的代碼假定數據庫用戶和密碼爲$dbusername, $dbpassword,數據庫的名稱爲$nameofdb

$date_addedprepare()調用中被替換爲參數: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); 

?> 
+0

謝謝Michael!這是完美的。感謝PDO鏈接。 –

+0

如果我想打印結果而不是打印,代碼如下: '$ json = json_encode($ result);'而不是: 'print_r($ result);' 對於最後一行? –

+1

@DonS'echo json_encode($ result);' –