Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PDO and MySQL 'between'

Tags:

sql

php

mysql

pdo

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?

like image 952
Samsquanch Avatar asked Sep 20 '12 14:09

Samsquanch


People also ask

What is difference between PDO and MySQL?

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.

Does PDO work with MySQL?

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.

Can I use PDO and MySQLi together?

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.

What is use of between and in MySQL?

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.


2 Answers

Don't wrap the values with single quote.

$STH = $DBH->prepare("SELECT * FROM `table` WHERE `start_date` BETWEEN :start_date AND :end_date");
like image 108
John Woo Avatar answered Sep 23 '22 01:09

John Woo


Do not put quotes around params:

$STH = $DBH->prepare("SELECT * FROM `table` WHERE `start_date` BETWEEN :start_date AND :end_date");
like image 35
Mihai Iorga Avatar answered Sep 26 '22 01:09

Mihai Iorga