Question

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, .....)

Was it helpful?

Solution

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.

OTHER TIPS

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

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top