I just started with PHP and mySQL and I'm creating some kind of blog. At time I think it's going well - I just got some trouble with my archives code.
I think the solution will be pretty easy but I'm so blinded that I just can't find the point on my own.
This is my actual code and everything works fine, also the links:
$sql = mysql_query ("SELECT YEAR(date) AS get_year, MONTH(date) AS get_month, COUNT(*) AS entries FROM blogdata GROUP BY get_month ORDER BY date ASC") or die('No response from database.');
while ($row = mysql_fetch_array($sql)) {
$get_year = $row["get_year"];
$get_month = $row["get_month"];
$entries = $row["entries"];
// get month name
$this_month = date( 'F', mktime(0, 0, 0, $row["get_month"]) );
echo '<dl>';
echo '<dt>Entries from '. $get_year . '</dt>';
echo '<dd><a href="archives.php?month='. $get_month .'">Entries from '. $this_month . ' </a>(' . $entries . ')</dd>';
echo '</dl>';
}
Ok. Then the result in the browser looks similar like this:
- Entries from 2012
- Entries from January (2)
- Entries from 2012
- Entries from February (1)
Now my question: How can I resume all months inside the year? Like this:
- Entries from 2012
- Entries from January (2)
- Entries from February (1)
I'm scared about creating a 12-months array cause maybe not every month there will be entries, and I don't want to show empty months.
Can someone help me? Thanks!!
---------------
Here I am again to show the final (working!!) result of your friendly help:
At least, I used Sam's version cause it was just for what i was looking for. I really appreciate the other answers - specially 'cause now I have more stuff to think about for the next tries.
Sam's code worked just awesome... the only trouble I had was, that after using the array, it only printed out 'December' as months.
So I looked over again the code and after 2 hours of seek and try, I found the point of trouble. It was nested in the following line:
$this_month = date( 'F', mktime(0, 0, 0, $row['get_month']) );
Changing it (It's logic, but for me as greenhorn it toke me a while) to:
$this_month = date( 'F', mktime(0, 0, 0, $month['get_month']) );
Now everything work fine. Just how I expected. So this is the working final code:
$sql = mysql_query ("SELECT YEAR(date) AS get_year, MONTH(date) AS get_month, COUNT(*) AS entries FROM blogdata GROUP BY get_year, get_month ORDER BY date ASC") or die('No response from database.');
$entries = array();
while ($row = mysql_fetch_assoc($sql)) {
$entries[$row['get_year']][] = $row;
}
foreach($entries as $year => $months) {
echo '<dl>';
echo '<dt>Entries from '. $year . '</dt>';
foreach($months as $month) {
$this_month = date( 'F', mktime(0, 0, 0, $month['get_month']) );
echo '<dd><a href="archives.php?month='. $month['get_month'] .'">Entries from '. $this_month . ' </a>(' . $month['entries'] . ')</dd>';
}
echo '</dl>';
}
Thanks to all again!