Reputation: 169
I have a query that selects all rows of data from a table in my database. I am using PHP and MySQL. Instead of grabbing all of the rows in my table, I would like to only grab rows that are between now and two weeks old. How can I do this? I know I would need to add a WHERE clause
My Code So far:
$notifications_query= "SELECT * FROM notifications ORDER BY recieved DESC";
The column containing the date that will be used is named 'viewed' and it is in 'datetime' format.
Thanks!
Upvotes: 2
Views: 995
Reputation: 1753
You've had an assortment of answers, because there are a whole bunch of ways to do this -- and some subtleties.
The simplest, if your received value is NEVER in the future, is to do something like...
WHERE received > DATE_SUB( CURDATE(), INTERVAL 14 DAY )
or
WHERE DATEDIFF( CURDATE(), received ) < 14
If your received value can be in the future as well, and you just want the slice from 14 days ago to today, that's not much trickier:
WHERE received BETWEEN DATE_SUB( CURDATE(), INTERVAL 14 DAY ) AND CURDATE()
or again,
WHERE DATEDIFF( CURDATE(), received ) BETWEEN 0 AND 14
One thing you should think about in addition to this: is received a date field, or a datetime field? CURDATE() is always midnight of today when compared to a datetime, so these BETWEEN queries may actually omit datetimes that fall during the course of today -- as they will fall after (e.g.) 2013-06-19 00:00:00, the datetime value of CURDATE. If that's an issue for you, use NOW() instead.
Upvotes: 0
Reputation: 23510
Try this
$notifications_query= "SELECT * FROM notifications WHERE yourdatecolumn BETWEEN DATE_SUB(NOW(), INTERVAL 2 WEEK) AND NOW() ORDER BY recieved DESC";
Upvotes: 2
Reputation: 1503
Try this
$notifications_query= "SELECT * FROM notifications WHERE viewed BETWEEN START_DATE AND END_DATE ";
received definition must be date in order for the query to work.
Upvotes: 0
Reputation: 17991
You can use a where clause that contains the datediff() function explained here
http://www.w3schools.com/sql/func_datediff.asp
Upvotes: 1
Reputation: 1231
I think this should do the trick:
$twoweeksago = time()- (3600*24*14);
$notifications_query= "SELECT * FROM notifications WHERE viewed > {$twoweeksago} ORDER BY recieved DESC";
Upvotes: 0