我有一个表格,里面有产品价格模型成本库存等,为了更容易,我计算出每个产品的客户总付款,比如这个
<?php echo number_format($show['quantity'] * $show['product_price'],0,',','.'); ?>
我需要显示这个计算的总和,但正如你所看到的,它们是在PHP中实时计算的。有办法做到吗?
这是完整的代码
<?php
$result=mysqli_query($database,"SELECT * FROM `products` order by `category` ASC");
$rows=mysqli_num_rows($result);
if(mysqli_num_rows($result)>0){
?>
<table class="sales">
<tr>
<td>Quantity</td>
<td>Product Cost</td>
<td>Customer Pays</td>
</tr>
<?php if($rows){$i=0;while($show=mysqli_fetch_assoc($result)){?>
<tr>
<td><?php echo number_format($show['quantity'],0,',','.'); ?></td>
<td><?php echo number_format($show['product_cost'],0,',','.'); ?></td>
<td><?php echo number_format($show['quantity'] * $show['product_cost'],0,',','.'); ?></td>
</tr>
<?php }}?>
</table>
TOTAL CUSTOMER PAY FOR ALL PRODUCTS = EXAMPLE $10.234
如果结果中有5种不同的产品具有不同的价格和不同的客户付款,我需要对所有这些客户付款进行汇总,并在此处显示
<?php }else{?>
No products to show
<?php }?>
编辑:已解决
解决方案是
<?php
$count = mysqli_query($database, "SELECT SUM(stock * cost) AS totalPaid
FROM products");
while($total = mysqli_fetch_assoc($count)){
echo number_format($total['totalPaid'],0,',','.');} ?>
感谢McAdam331 的正确答案
您可以将SUM
添加为SQL查询的一部分:
SELECT SUM(quantity * product_cost) AS totalPaid
FROM myTable
GROUP BY customer;
我只是猜测你会根据问题中的线索对客户进行分组,但你可以根据需要进行更改。