我希望打印去年每个月数据库中一列的总数。到目前为止,我这样做的代码是:
$month = date("n");
$year = date("Y");
$loop = 12;
while($loop>1) {
$first = mktime(0,0,0,$month,1,$year);
$last = mktime(23,59,00,$month+1,0,$year);
$spendingData = mysql_query("SELECT * FROM spending WHERE date BETWEEN $first AND $last") or die(mysql_error());
$totalMonth = 0;
while($spending = mysql_fetch_array($spendingData))
{
$totalMonth = $totalMonth + $spending['amount'];
}
print "£".$totalMonth;
$loop = $loop-1;
print "<br>";
}
我的问题是,在循环中,我如何调整每个月的时间?我考虑过只花一个月的时间来远离时间戳,但由于我不知道每个月有多少天,我认为这行不通。我也不认为我可以继续从月数中拿走 1,因为这不会解释多年。我也不想硬编码这些数字,因为它们会随着每个新的月而变化。
我怎样才能做到这一点?
谢谢
你可以在MySQL中相当微不足道地做到这一点:
SELECT MONTH(date) AS month, SUM(amount) AS amount
FROM yourtable
WHERE YEAR(date) = $year
GROUP BY MONTH(date)
而不必让PHP参与日期操作。