Jump to content

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


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.

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.