在使用PDO的查询中使用传递的变量 [英] Using a passed variable in a query using PDO

查看:73
本文介绍了在使用PDO的查询中使用传递的变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to take a variable passed from another page and use it in a PDO query. The variable is the date the record was added and I'm trying to return all the newer records. Do I use $_POST for this in 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);


?>

推荐答案

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

You need to actually establish a connection to the database by creating a new PDO object into $dbh. The code below assumes a database user and password as $dbusername, $dbpassword and database named $nameofdb.

$date_added替换为参数:dateadded,然后通过数组传递给execute()调用.

$date_added is replaced in the prepare() call with a parameter :dateadded, then passed via an array to the execute() call.

请同时阅读 PDO::__construct() PDO::execute()

Please read the documentation on both PDO::__construct() and 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);

?>

这篇关于在使用PDO的查询中使用传递的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆