Search code examples
phpmysqlwhile-looparchive

create monthly archive with PHP and MySQL


I'm trying to create a news archives in my website. i wrote this code:

$sql_result = $db->query("
SELECT *,COUNT(id) AS itemCount 
FROM post 
GROUP BY DATE_FORMAT(date, '%Y-%m') DESC ");

while ( $row = $db->get_row( $sql_result ) ) {
 $datetime = strtotime($row['date']);
 $tday = date("Y-m", $datetime);
 $count = $row['itemCount'];
 echo "Month: {$tday} - News Number: {$count}<br>";
}

And this is the result:

Month: 2013-06 - News Number: 4
Month: 2013-05 - News Number: 3
Month: 2013-04 - News Number: 4
Month: 2013-03 - News Number: 3

My question is, how i can show news title's in every months after that month? for example something like this:

Month: 2013-06 - News Number: 4
 -news number 1 for this month
 -news number 2 for this month
 -news number 3 for this month
 -news number 4 for this month
Month: 2013-05 - News Number: 3
 -news number 1 for this month
 -news number 2 for this month
 -news number 3 for this month
Month: 2013-04 - News Number: 4
 -news number 1 for this month
 -news number 2 for this month
 -news number 3 for this month
 -news number 4 for this month
Month: 2013-03 - News Number: 3
 -news number 1 for this month
 -news number 2 for this month
 -news number 3 for this month

Solution

  • Try using this code.

     while ( $row = $db->get_row( $sql_result ) ) {
      $datetime = strtotime($row['date']);
      $tday = date("Y-m", $datetime);
      $count = $row['itemCount'];
      echo "Month: {$tday} - News Number: {$count}<br>";
      $sql_result1 = $db->query("
      SELECT newsTitle 
      FROM post 
      WHERE DATE_FORMAT(date, '%Y-%m')=DATE_FORMAT({$datetime}, '%Y-%m')");
      while($row1 = $db->get_row( $sql_result1 ) ){
       echo "News: {$row1['newsTitle']}";
      }
     }