如何对总列的值求和,即计算子总数?总数不是来自数据库

时间:2018-02-27 12:16:22

标签: php

enter image description here *现在我如何计算这些值不是来自数据库的(tolal)字段值的子总数,这些值来自(商品价格*数量)*

这是我的代码:

 <?php
$ipAdd = getRealIpAddr();

     $checkPrice= "select * from cart where ipAdd= '$ipAdd' ";
     $run= mysqli_query($conn,$checkPrice);
     while($record= mysqli_fetch_array($run)){

     $proId= $record['pId'];
     $cId= $record['cId'];
     $cQuant= $record['qnty'];


     $proPric= "select * from products where prodId= '$proId' ";
     $runPrice=mysqli_query($conn, $proPric);
     while($pPrice=mysqli_fetch_array($runPrice)){

         $proPri= $pPrice['prodPrice'];

         $t = $proPri* $cQuant ;
     }
     }
?>

1 个答案:

答案 0 :(得分:2)

好的,所以假设你想要所有商品的总数乘以所有的数量,这就是你做的:

$ipAdd = getRealIpAddr();
$total = 0;
$checkPrice = "SELECT * FROM cart WHERE ipAdd = '$ipAdd' ";
$run = mysqli_query($conn,$checkPrice);
while($record = mysqli_fetch_array($run)){
    $proId = $record['pId'];
    $cId = $record['cId'];
    $cQuant = $record['qnty'];
    $proPric = "SELECT * FROM products WHERE prodId = '$proId' ";
    $runPrice = mysqli_query($conn, $proPric);
    $pPrice = mysqli_fetch_array($runPrice);
    $proPri = $pPrice['prodPrice'];
    $t = $proPri * $cQuant ;
    $total += $t;
}
echo $total; // will be a sum of all prices times all quantities
  • 如果您只提取一个值,那么您不需要while,只需删除它就可以了。
  • 您可以通过声明$total变量来启动此过程,在这种情况下重置它
  • 你做了你已经做过的所有事情,然后按$total
  • 的值增加$t

请注意,$total在此while循环期间会发生变化,因此考虑到这看起来像是每用户查询,请务必在循环之外使用它。