MySQL PHP:博客文章存档下拉菜单

时间:2015-02-04 19:37:56

标签: php mysql archive

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

目前我正在尝试为我的帖子创建一个存档菜单,这些菜单在我的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月份的第二个职位名称

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

$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();
 ?> 

谢谢!

1 个答案:

答案 0 :(得分:1)

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

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,如果它们不为零,则必须在打开新的之前关闭它。