MySQL PHP:博客 Post 存档下拉菜单

MySQL PHP: Blog Post Archive Drop Down Menu

我是 MySQL 和 PHP 的新手,只是有几个问题。

目前,我正在尝试为我的 post 创建一个存档菜单,这些菜单在我的 MySQL 数据库中查找,名为 "posts"。

它应该看起来像,

2010 (2)
   September (2)
     Bellavisa
     Mists of Netting

   July (1)
     Turkey is cool!

2009 (1)
   May (1)
     Cock of the Rock

但我目前得到,

2010 (2)
   September (2)
     Bellavisa


   July (1)
     Turkey is cool!

2009 (1)
   May (1)
     Cock of the Rock

因此,我错过了 9 月

下的第二个 post 标题

如有任何帮助,我们将不胜感激!我的代码在下面!

$sql = "SELECT Month(time) as Month, Year(time) as Year,
title, COUNT(*) AS total FROM posts GROUP BY Year, Month ORDER BY time DESC";
$stmt = $conn->query($sql);

$currentMonth = 0;

$currentYear = 0;

if ($stmt->num_rows > 0) {
while($row = $stmt->fetch_assoc()){
  $title = $row["title"];
     // if the year changes you have to display another year
    if($row['Year'] != $currentYear) {

        // reinitialize current month
        $currentMonth = 0;

        // display the current year
        #echo "<li class=\"cl-year\">{$row['Year']} ({$row['total']})</li>";
echo "          <ul>";
echo "          <li onClick = 'show(\"{$row['Year']}\")' > <img src='images/triangle_closed.gif' id=img_{$row['Year']}>{$row['Year']} ({$row['total']})</li>\n"; 
echo "          <li>\n"; 
echo "          <ul id = {$row['Year']} style='display:none;'>\n"; 
#echo "</ul>";



        // change the current year
        $currentYear = $row['Year'];
    }

    // if the month changes you have to display another month
    if($row['Month'] != $currentMonth) {

        // display the current month
        $monthName = date("F", mktime(0, 0, 0, $row['Month'], 10));
#echo "<ul>";
echo "              <li onClick = 'show(\"{$row['Year']}$monthName\")' > <img src='images/triangle_closed.gif' id=img_{$row['Year']}$monthName>$monthName ({$row['total']})</li>\n"; 
echo "              <li>\n"; 
echo "                <ul id = {$row['Year']}$monthName style='display:none;'>\n"; 
echo "                  <li class='cl-posts active'><a href='\base\item.php?id=$title'>".$title."</a></li>\n"; 
echo "                </ul>\n"; 
echo "              </li>\n"; 
        #echo "<li class=\"cl-month\">$monthName ({$row['total']})</li>";

        // change the current month
        $currentMonth = $row['Month'];
    }

    // display posts within the current month
    #echo "<li class='cl-posts active'><a href='\base\item.php?id=$title'>".$title."</a></li>";
}
}

 $conn->close();
 ?> 

谢谢!

查看您的查询,您按年份分组,因此不显示第二个标题是正常的,而且您正在尝试计算年数。我建议混合一个子查询,这样你就可以得到两个结果,所以改变

SELECT Month(time) as Month, Year(time) as Year, title, COUNT(*) AS total FROM posts GROUP BY Year, Month ORDER BY time DESC

SELECT Month, Year, p.title, t.total
FROM posts p 
INNER JOIN (SELECT DISTINCT Year(time) Year, Month(time) Month, SUM(1) FROM posts GROUP BY Year, Month) t ON t.Year = Year(p.time) AND t.Month = Month(p.time)
ORDER BY time DESC

此外,对于标识问题,您在关闭最后一个之前打开新的,每次更改年或月。

验证 $currentYear 和 $currentMonth,如果它们是 non-zero,您必须在打开新的之前关闭。