在我的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
<?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> ";
?>
在循环中声明$ total out while循环为$ total = 0,在循环内写入$ total = $ total +($ order * $ duration)
跟踪新变量中的总和..
<?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>";
?>
在循环之前定义一个变量,它将包含所有记录的总和:
$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
。
如果你不需要一次打印出每一个,那么你可以在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'];