I'm trying to get PDO to work with a MySQL 'between'. Below is my code:
$DBH = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass);
$start_date = date('Y-m-d H:i:s', mktime(0, 0, 0, 11, 1, 2009));
$end_date = date('Y-m-d H:i:s', mktime(23, 59, 59, 11, 30, 2009));
$STH = $DBH->prepare("SELECT * FROM `table` WHERE `start_date` BETWEEN ':start_date' AND ':end_date'");
$STH->bindParam(':start_date', $start_date, PDO::PARAM_STR);
$STH->bindParam(':end_date', $end_date, PDO::PARAM_STR);
$STH->execute();
var_dump($row);
What gets returned is an array with '0' or 'NULL' for values. When I hard code the end date, it acts as if start_date
is set to -1, retuning me all rows before the end_date
. So, what am I doing wrong here?
MySQLi is a replacement for the mysql functions, with object-oriented and procedural versions. It has support for prepared statements. PDO (PHP Data Objects) is a general database abstraction layer with support for MySQL among many other databases.
PDO will work on 12 different database systems, whereas MySQLi will only work with MySQL databases. So, if you have to switch your project to use another database, PDO makes the process easy. You only have to change the connection string and a few queries.
For example, to insert data using MySQLi and then select and work with it using PDO in other part of the project? I have a lot of insert/update code in MySQLi, but decided to switch to PDO? Yes, it is possible. The data inserted in to a database doesn't care how it got there, or how you get it back out again.
The BETWEEN operator selects values within a given range. The values can be numbers, text, or dates. The BETWEEN operator is inclusive: begin and end values are included.
Don't wrap the values with single quote.
$STH = $DBH->prepare("SELECT * FROM `table` WHERE `start_date` BETWEEN :start_date AND :end_date");
Do not put quotes around params:
$STH = $DBH->prepare("SELECT * FROM `table` WHERE `start_date` BETWEEN :start_date AND :end_date");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With