By using this site you agree to the use of cookies by Brugbart and our partners.

Learn more

MySQL select between dates

How to select all rows between some given dates using MySQL and PHP.

Edited: 2015-07-10 16:41

To make mysql select between dates, whether you are using readable dates, or unix stamps, you can use the AND keyword operator to add more conditions.

The below is a example of a MySQL query selecting all the rows in a given time-range, these are then returned with a PHP While Loop.

SELECT * FROM Calender WHERE PostTime > '2011-01-01 00:00:00' AND PostTime < '2012-01-01 00:00:00' ORDER BY PostTime ASC

The ORDER BY PostTime ASC part, will order the selection by the post time, and output the oldest first (ASC). To do the opposite use (DESC) instead.

The date/time format is YYYY-mm-dd HH:ii:ss, The order would be Year, months, days, hours, minutes and seconds. You can create a time stamp formated like this using the date function of PHP.

echo date("Y-m-d H:i:s");

To use a query like the above in PHP, simply wrap it in double quotes, and assign it to a variable. You can then run the mysql_query function.

$query = "SELECT * FROM Calender WHERE PostTime > '2011-01-01 00:00:00' AND PostTime < '2012-01-01 00:00:00' ORDER BY PostTime ASC";
$result = mysql_query($query) or die(mysql_error());

 while($row = mysql_fetch_array($result)) {
  echo $row['PostTime'] . '<br>';
 }