doushangxianq07480 2015-06-29 20:01
浏览 27
已采纳

动态计算php mysql结果总和

I have a table with product price model cost stock etc, to make it easier I calculate the total customer pay for for each product like this

<?php echo number_format($show['quantity'] * $show['product_price'],0,',','.'); ?>

I need to show the total sum of this calculation but as you can see they are calculared in PHP real time. Is there a way to do it?

Here is the complete code

<?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

If there are 5 different products in the results with different prices and different Customer Pays I need to sum all those Customer Pays and show here

<?php }else{?> 

No products to show

<?php }?>

EDIT: SOLVED

The solution is

<?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,',','.');} ?>

Thanks to the correct answer of McAdam331

  • 写回答

1条回答 默认 最新

  • doudizhi947129 2015-06-29 20:03
    关注

    You can add the SUM as part of your SQL query:

    SELECT SUM(quantity * product_cost) AS totalPaid
    FROM myTable
    GROUP BY customer;
    

    I'm just guessing you'd group on customer based on the clues in your question, but you can change that to whatever you need.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 数学建模,尽量用matlab回答,论文格式
  • ¥15 昨天挂载了一下u盘,然后拔了
  • ¥30 win from 窗口最大最小化,控件放大缩小,闪烁问题
  • ¥20 易康econgnition精度验证
  • ¥15 msix packaging tool打包问题
  • ¥28 微信小程序开发页面布局没问题,真机调试的时候页面布局就乱了
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能