我希望打印去年每个月数据库中一列的总计。到目前为止,我要执行此操作的代码是:
$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 参与日期操作。
关于php - 如何循环获取过去十二个月开始和结束的 unix 时间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14524825/