Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way of SELECT based on DATE in PHP/MYSQL

Tags:

date

php

mysql

I have a database table with column DATETIME called 'entry_date', such as...

ID  entry_date
1   2012-10-13
2   2012-10-14
3   2012-10-15
4   2012-10-20
5   2012-10-20
6   2012-10-21

Whats the best way of echoing out the result for based on DATE in PHP/MYSQL, so i get just the results for this week so 2012-10-15 > 2012-10-21, but obviously i can't just code that out because days change, everyday :) so how would you do that in php so tomorrow the condition for this week would be 2012-10-16 > 2012-10-22

like image 384
CarlRyds Avatar asked Oct 20 '12 23:10

CarlRyds


1 Answers

For today, use

where date(`entry_date`) = curdate()

For this month,

where month(`entry_date`) = month(curdate()) 
and  year(`entry_date`) = year(curdate()) 

For this week

WHERE `entry_date` 
BETWEEN (CURDATE() - Interval DAYOFWEEK(CURDATE()) day) 
AND (CURDATE() - Interval DAYOFWEEK(CURDATE()) day + Interval 1 week)

Above query is good for understanding. But not good for performance point of view. See the bellow modified one. Its far better.

SET @s:=(CURDATE() - Interval DAYOFWEEK(CURDATE()) day)
SET @e:=(CURDATE() - Interval DAYOFWEEK(CURDATE()) day + Interval 1 week)
SELECT ....  WHERE `entry_date` BETWEEN @s AND @e

Here DAYOFWEEK function returns an integer number starting from 1=Sunday. So your weeks will be counted as Saturday as starting date. If you want Monday add + Interval 2 day with Interval.

It can be also simplified to the following. But it does not support any day as first day of week. So its not portable to all culture.

where yearweek(`entry_date`) = yearweek(curdate())
like image 170
Shiplu Mokaddim Avatar answered Nov 03 '22 01:11

Shiplu Mokaddim