PHP& SQL,查询嵌套的年,月和自定义博客的帖子数

时间:2014-06-09 02:59:50

标签: php mysql sql

我想在链接中显示年份,月份以及博客帖子数量的存档列表。像这样:

  • 2013

    • 十二月(3)
  • 2014

    • 1月(4)
    • 二月(2)

...等,它将链接到一个页面,在那里它将显示该月的所有帖子。

我试过了:

SELECT YEAR(date) as year, MONTH(date) as month, .... 

并在php中完成:

<ul>
  <li><?php echo $year; ?>
      <ul>
         <li><?php echo $month; ?> (<?php echo $countpost; ?>)</li>
      </ul>
  </li>
</ul>

但我只是得到一个空白页面,我很确定我的查询错误。

编辑:添加数据库

postid | title | date | content | userid | active

2 个答案:

答案 0 :(得分:0)

试试这个:

SELECT YEAR(date) as year, MONTH(date) as month, COUNT(postid) as countpost
FROM postTable
GROUP BY YEAR(date), MONTH(date);

在演示中查看更多内容:SQL Fiddle

答案 1 :(得分:0)

使用这些查询获得类似于您所描述的输出。

<?php
$con=mysqli_connect("localhost","root","","my_db");

$result=mysqli_query($con,"select distinct YEAR(date) as myyear from table");

while($fetch=mysqli_fetch_array($result))

{

echo "<b>".$fetch['myyear']."</b><br />";

$q1="select MONTH(date) as postmonth,count(*) as postcount from table where year(date)=".$fetch['myyear']." group by MONTH(date)";
$temp1=mysqli_query($con,$q1);
while($temp=mysqli_fetch_array($temp1))

echo "<b>".$temp['postmonth']."</b> (".$temp['postcount'].")<br />";

}

mysqli_close($con);
?>

希望它有所帮助。