I’m building a mini news CMS where the news added are sorted using a DATE type column e.g. INSERT date_posted=NOW(), etc.
I can then easily list out all the available months with: SELECT DATE_FORMAT(date_posted, '%M %Y') as date_posted. This makes the monthly categories list.
The issue I’m having is with displaying all the news by a particular month. I have tried to pass the date_posted variable in the URL but have failed to actually incorporate it in my Query. If for instance, I try WHERE date_posted=\"2009-10-16\", the result is all the news of that day. WHERE date_posted=\"2009-10\" doesn’t work on the other hand.
I’ve passed this parameter in the URL DATE_FORMAT(date_posted, '%M%Y') as month which echos out October2009 for example. Then WHERE date_posted=$month returns nothing because firstly I’m guessing it’s in the wrong format, secondly, the MySQL data type does not output what I want as evidenced by the aforementioned hard-coded example.
Please help,
Thanks!
You should use a range in your
whereclause:To get the “2009-10-01” and “2009-11-01” dates, you can use PHP’s
strtotimeanddatefunctions:You could also use the
yearandmonthfunctions, but then you won’t get any benefit from any indexes you might be able to use, so it’s generally not as good a solution as the range. An example: