2011-10-26 50 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);' –