while循环内的SUM值

时间:2019-01-20 14:12:13

标签: php mysql

在我的PHP页面中,我有一个while循环,显示“客户订单总数”表。我想获取while循环中所有Totals值的总和。这是我的代码相关部分目前的样子:

<?php

include'includes/config.php';
$sql ="Select * from new_booking order by order asc";
$re = mysqli_query($mysqli,$sql);

while($row=mysqli_fetch_array($re)) { 
    $order    =   $row['order'];
    $duration =   12;
    $total = $order * $duration;

    echo " <p> $total </p>";
  // echo "<p> All Sumtotals should display here </p> ";

}

?> 

7 * 12 = 84
8 * 12 = 96
总和= 180

5 个答案:

答案 0 :(得分:2)

<?php

include'includes/config.php';
$sql ="Select * from new_booking order by order asc";
$re = mysqli_query($mysqli,$sql);
$total = 0;
while($row=mysqli_fetch_array($re)) { 
    $order    =   $row['order'];
    $duration =   12;
    $total = $total + ($order * $duration);


}

    echo " <p> $total </p>";
  // echo "<p> All Sumtotals should display here </p> ";

?> 

答案 1 :(得分:2)

在while循环外部声明$ total为$ total = 0,在循环内部写入$ total = $ total +($ order * $ duration)

答案 2 :(得分:2)

跟踪新变量中的总数。

<?php

include'includes/config.php';
$sql ="Select * from new_booking order by order asc";
$re = mysqli_query($mysqli,$sql);
$sumTotal = 0;

while($row=mysqli_fetch_array($re)) { 
    $order    =   $row['order'];
    $duration =   12;
    $total = $order * $duration;
    $sumTotal = $sumTotal + $total;
    echo " <p> $total </p>";
    echo " <p> Running total $sumTotal </p>";
}
echo " <p> Grand total $sumTotal </p>";
?> 

答案 3 :(得分:1)

在循环之前定义一个变量,该变量将包含所有记录的总和:

$sumTotal = 0;

while($row = mysqli_fetch_array($re)) { 
    $order    = $row['order'];
    $duration = 12;
    $total    = $order * $duration;

    // Add this records total to the sum total
    $sumTotal += $total;

    echo "<p> $total </p>";
}    

echo "<p>Here's the sum total: $sumTotal</p>";

这将为您提供每个记录的总数,然后为之后的所有记录的总数。

如果您想查看每条记录的总数(以查看总数的增加),则只需在循环内回显$sumTotal而不是$total

答案 4 :(得分:0)

如果您不需要一次打印出每个总数,则可以在SQL语句中执行,将所有order值(* 12)求和,并为其指定别名更容易访问...

$sql = "SELECT SUM(`order` * 12) AS total FROM new_booking";
$run = mysqli_query($mysqli, $sql);
$row = mysqli_fetch_assoc($run);
echo $row['total'];