开发者

Monthly categories with MySQL DATE Type

开发者 https://www.devze.com 2022-12-09 14:57 出处:网络
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'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 al开发者_如何学JAVAl 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 where clause:

where   date_posted >= cast('2009-10-01' as date)
    and date_posted <  cast('2009-11-01' as date)

To get the "2009-10-01" and "2009-11-01" dates, you can use PHP's strtotime and date functions:

$date_from_querystring = "2009-10";
$start_date = $date_from_querystring . "-01";
$end_date = date("Y-m-d", strtotime($start_date . " +1 month"));

You could also use the year and month functions, 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:

where year(date_posted) = 2009 and month(date_posted) = 10
0

精彩评论

暂无评论...
验证码 换一张
取 消