Jump to content

I need to output/group a query by month/year.


ssailer

Recommended Posts

I have a query which is using a date function to format an article date by month/year.  My query is:

 

SELECT `ID`, `title`, `content`, `articleDate`, `pdfDoc`, date_format(articleDate, '%M %Y') as monthYear from articles ORDER BY articleDate DESC";

 

The query is working fine, but I cannot figure out how to output it on screen grouped by month/year.  I need it to look something like the following:

 

August 2009

    - Article Title

    - Article Title

 

September 2009

    - Article Title

    - Article Title

 

I am a ColdFusion programmer who is trying to learn PHP and this is beyond my skill level right now...

 

Thank you!

 

SELECT `ID`, `title`, `content`, `articleDate`, `pdfDoc`, date_format(articleDate, '%M %Y') as monthYear from articles ORDER BY monthYear, articleDate DESC

 

$current = null;
while ($row = mysql_fetch_assoc($result)) {
  if ($current !== $row['monthYear']) {
    $current = $row['monthYear'];
    echo '<dt>', $row['monthYear'], '</dt>';
  }
  echo '<dd>', $row['title'], '</dd>';
}

 

I modified your query so that it orders by monthYear first and articleDate afterwards (thus all monthYear will be grouped together). Afterwards I added a $current which will hold the current monthYear (August 2009 first, September 2009 second, ..) and print it once.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.