tags:

views:

57

answers:

3

I am writing custom code to create a blog. I need the archives page to list all the blog entries by month. I cannot come up with a way to do that. I guess it should not be too tough as it is a common feature on all blogs. The table structure is (postid, posttitle, publishdate, .....)

A: 

If your entries come from a SQL database, it's easiest to ask that to perform the sort for you using an ORDER BY. Something like

select * from posts order by publishdate
Adam Wright
A: 

Something like this pseudo-code:

SELECT `publishdate` FROM `entries` ORDER BY DESC `publishdate` GROUP BY YEAR(`publishdate`), MONTH(`publishdate`);
foreach ($dates as $date) {
    $date = mysql_real_escape_string($date)
    SELECT * FROM `entries` WHERE `publishdate` = $date
}

I think.

Ollie Saunders
There's a typo: MOUTH/MONTH
Rew
Firstly, this won't work since publishdate isn't the same for all the posts in a month.Secondly, SQL queries should never happen in such a loop.
Leonid Shevtsov
@Leonid: Why not?
Ollie Saunders
+2  A: 

I'm not sure I understand the question, but if you want just numbers of all posts per month, use a query like this:

SELECT DATE_FORMAT(publishdate, '%Y%m') AS publishmonth, count(*) AS entrycount
FROM entries GROUP BY DATE_FORMAT(publishdate, '%Y%m')

If you want all posts for a particular month:

SELECT * FROM entries WHERE publishdate > '2009-01' AND publishdate < '2009-02';

And if you want to list all posts grouped by month on a single page, just select them sorted by publishdate and do the grouping locally.

Lukáš Lalinský