如何用php和mysql按月分解报告?

wil*_*fun 2 php mysql

我想在这里做一些相对简单的事情.基本上我有一个表,其中有一堆行标有时间戳(格式:2009-05-30 00:14:57).

我想要的是一个查询,它会拉出所有行,然后按月拆分它们,所以我留下了最终结果,如:

2月
rowID名称订单日期
rowID名称订单日期
rowID名称订单日期

1月份
rowID名称订单日期
rowID名称订单日期
rowID名称订单日期

等等

我有一些模糊的想法如何做到这一点 - 他们似乎只是啰嗦.

其中一种方法是每个月进行一次查询.我将得出当前月份在PHP中的内容然后构造一个for(),它可以追溯到几个月.

喜欢:

$currentmonth = 8;

$last6months = $currentmonth - 6;

for($i = $currentmonth; $i == $last6months; $i--) {

     $sql = 'SELECT * FROM reports WHERE MONTH(reports.when) = $currentmonth ';  

     $res = mysql_query($sql);


     // something would go here to convert the month numeral into a month name $currentmonthname

     echo $currentmonthname;

     while($row = mysql_fetch_array($res)) {

           // print out the rows for this month here


     }

}
Run Code Online (Sandbox Code Playgroud)

有一个更好的方法吗?

Sve*_*lov 5

最好一次获取所有数据,按月排序.

然后在使用php获取时,您可以将当前月份存储在变量中(例如$ curMonth),如果月份有变化,则回显"新月"...

执行查询的速度很慢,最好尽量减少与数据库的"对话".