Reputation: 134
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);
?>
Upvotes: 0
Views: 4047
Reputation: 270599
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
is replaced in the prepare()
call with a parameter :dateadded
, then passed via an array to the execute()
call.
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);
?>
Upvotes: 2