Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select data between two dates?

I'm using a database to store logs, with a column "date" which holds the date it was inserted. The format of the date is "MM/DD/YY". Please can anyone suggest how I would SELECT data in between two certain dates. For example, I tried this:

$from_date = "01/01/12";
$to_date = "02/11/12";

$result = mysql_query("SELECT * FROM logs WHERE date >= " . $from_date . " AND date <= " . $to_date . " ORDER by id DESC");

while($row = mysql_fetch_array($result)) {
// display results here
}

But I guess this doesn't work because the dates aren't numbers. Thanks for the help! :)

like image 536
Joey Morani Avatar asked Nov 28 '22 18:11

Joey Morani


2 Answers

Use the BETWEEN keyword:

"SELECT * FROM logs WHERE date BETWEEN '" . $from_date . "' AND  '" . $to_date . "'
ORDER by id DESC"
like image 60
Sarfraz Avatar answered Nov 30 '22 07:11

Sarfraz


You can cast the fields as dates and then select between from_date and to_date

SELECT * FROM logs WHERE date STR_TO_DATE(date, '%m/%d/%Y') between STR_TO_DATE(from_date, '%m/%d/%Y') and STR_TO_DATE(to_date, '%m/%d/%Y')
like image 31
Brian Avatar answered Nov 30 '22 08:11

Brian