Php 我想每月更新一次';这是网站上的总销售额,但它只是更新了上一次的销售额

Php 我想每月更新一次';这是网站上的总销售额,但它只是更新了上一次的销售额,php,Php,我正在创建一个电子商务网站,在管理仪表板中,我想显示特定月份的总销售额。因此,我只是根据月份获取销售额,并进行while循环以访问每个销售额,以及if-else以检查一个月的销售额是否为空。但是有一个问题,它显示了上一次的销售忽略了其他的 <?php $thisYr = date("Y"); $lastYr = $thisYr - 1; $thisYrQ = $db->query("SELECT * FROM transactions WHERE YEAR(t

我正在创建一个电子商务网站,在管理仪表板中,我想显示特定月份的总销售额。因此,我只是根据月份获取销售额,并进行while循环以访问每个销售额,以及if-else以检查一个月的销售额是否为空。但是有一个问题,它显示了上一次的销售忽略了其他的

<?php
    $thisYr = date("Y");
    $lastYr = $thisYr - 1;
    $thisYrQ = $db->query("SELECT * FROM transactions WHERE YEAR(txn_date) = '{$thisYr}'");
    $lastYrQ = $db->query("SELECT * FROM transactions WHERE YEAR(txn_date) = '{$lastYr}'");
    $current = array();
    $last = array();
    $currentTotal = 0;
    $lastTotal = 0;
    while ($x = mysqli_fetch_assoc($thisYrQ)) {
        $month = date("m",strtotime($x['txn_date']));
        if (!array_key_exists($month,$current)) {
            $current[(int)$month] = $x['grand_total'];
        } else{
            $current[(int)$month] += $x['grand_total'];
        }
        $currentTotal += $x['grand_total'];
    }

    while ($y = mysqli_fetch_assoc($lastYrQ)) {
        $month = date("m",strtotime($y['txn_date']));
        if (!array_key_exists($month,$current)) {
            $last[(int)$month] = $y['grand_total'];
        } else{
            $last[(int)$month] += $y['grand_total'];
        }
        $lastTotal += $y['grand_total'];
    }
?>

既然你只对总数感兴趣,那就让mysql来做吧

SELECT SUM(grand_total) as grand_total, MONTH(txn_date) AS month FROM transactions WHERE YEAR(txn_date) = '{$thisYr}' GROUP BY MONTH(txn_date)
循环遍历结果并将其添加到数据中

while ($row = mysqli_fetch_assoc($q) ) {
   $data[$row['month']] = $row['grand_total'];
}
然后在foreach循环中执行以下操作

foreach (range(1, 12) as $month) {
   if ( exists($data[$month]) ){
       echo $data[$month];
   }else{
       echo "No data for month";
   }

这应该更快,花费更少的时间/内存…等等,因为你只对总数感兴趣,让mysql来做吧

SELECT SUM(grand_total) as grand_total, MONTH(txn_date) AS month FROM transactions WHERE YEAR(txn_date) = '{$thisYr}' GROUP BY MONTH(txn_date)
循环遍历结果并将其添加到数据中

while ($row = mysqli_fetch_assoc($q) ) {
   $data[$row['month']] = $row['grand_total'];
}
然后在foreach循环中执行以下操作

foreach (range(1, 12) as $month) {
   if ( exists($data[$month]) ){
       echo $data[$month];
   }else{
       echo "No data for month";
   }
这应该更快,花费更少的时间/内存…等等