在使用PDO的查询中使用传递的变量

时间:2011-10-26 14:01:30

标签: php mysql pdo

我正在尝试从另一个页面传递一个变量并在PDO查询中使用它。变量是记录添加的日期,我正在尝试返回所有较新的记录。我是否在PDO中使用$ _POST?

<?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 个答案:

答案 0 :(得分:2)

您需要通过在$dbh中创建新的PDO对象来实际建立与数据库的连接。下面的代码假定数据库用户和密码为$dbusername, $dbpassword,数据库名为$nameofdb

{p} $date_added已在prepare()调用中替换为参数:dateadded,然后通过数组传递到execute()调用。

请阅读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);

?>