PHP MYSQL Blog Archive Menu by Year and Month

五迷三道 提交于 2019-12-03 07:48:41

问题


I'm looking for an efficient way to collate all blog posts into a menu of the following format:

2012

  • August(6)
  • September(4)
  • October(2)

Month representing the month(obviously), and the value inside the brackets representing the number of posts in that month. Once clicked, a search will then be made for all posts in that month, in that year.

I need it to be dynamic, picking up November automatically when a post is created in that month, and carrying on into December, into 2013 etc etc...

All I have is a UNIX timestamp for each post. I would really like to avoid using seperate functions to gather endless comlex arrays etc.

Any help much appreciated.


回答1:


From your question, I understand you're trying to come up with a query to group a number of elements by month and year. The following should do the trick:

SELECT 
    YEAR(dateField) AS YEAR, 
    MONTH(dateField) AS MONTH,
    COUNT(*) AS TOTAL 
FROM table 
GROUP BY YEAR, MONTH

Obviously, "dateField" being the name of your datetime/timestamp column and "table" being the name of your table.

More information on the GROUP BY clause and aggregate functions (such as the COUNT(*) function used above) here.



来源:https://stackoverflow.com/questions/13053636/php-mysql-blog-archive-menu-by-year-and-month

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!