繁体   English   中英

如何在php中按月添加和获取销售?

[英]How to add and get sales by month in php?

我想在表中获得当月的销售额。 但它显示的是该月的最后一个订单,我希望在1月至12月的表格中以总计显示销售量。 就像在一月份,我得到了4辆oreder,每辆10美元,那么它将显示一月份的销售:40美元,而不是最后一笔10美元。 为此,我正在做:

$thisyear = $db->query("SELECT total_Price,order_date FROM orderTable WHERE YEAR(order_date) = '{$thisyear}'");

  $current = array();
  $currentTotal = 0;

 while($x = mysqli_fetch_assoc($thisyear)){
 $month = date("m-d-Y",strtotime($x['order_date']));
 if (!array_key_exists($month,$current)) {
  $current[(int)$month] = $x['total_Price'];

 }else{
   $current[$month] += $x['total_Price'];
   echo $current[$month]; // Here is the problem. This is not adding here like January = $40
 }
 $currentTotal += $x['total_Price'];
 }

我想添加该月的所有收入,并想逐月显示。 最后,$ currentTotal是该年的总收入。

您为什么不想要在SQL查询中汇总销售量,将其重写为:

$months = $db->query(sprintf("
SELECT SUM(total_Price) AS month_total,MONTH(order_date) AS month   
FROM orderTable 
WHERE YEAR(order_date) = '%s' 
GROUP BY MONTH(order_date)", 
$db->escape($thisyear)));

然后将其输出到模板中,就可以得出给定年份的所有月份的总和。

请注意,我添加了$db->escape()调用,以向您显示避免SQL注入的提示。 可能有不同的方法来转义注入查询的变量,但是您绝对可以使用它们-检查您的ORM或MySQL库文档。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM