Mohamed Saeed Ahmed
Mohamed Saeed Ahmed

Reputation: 15

SUM values inside while loop

In my PHP page, I have a while loop that displays the Total of Orders of Customers Table. I want to get the sum of all the Totals values in while loop. This is how the relevant sections of my code look at the moment:

<?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
Sum total = 180

Upvotes: 1

Views: 7171

Answers (5)

Nigel Ren
Nigel Ren

Reputation: 57121

If you don't need to print out each total one at a time, you could do this in the SQL statement instead, sum up all the order values (*12) and give it an alias to make it easier to access...

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

Upvotes: 1

M. Eriksson
M. Eriksson

Reputation: 13635

Define a variable before the loop that will contain the sum total of all records:

$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>";

This will give you the total for each record and then the sum total of all records after.

If you rather want to see the sum total on each record (to see it increasing), then just echo $sumTotal instead of $total inside the loop.

Upvotes: 1

Matthew Page
Matthew Page

Reputation: 756

Keep track of the sum total in a new variable..

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

Upvotes: 3

Varun Setia
Varun Setia

Reputation: 165

Declare $total outside while loop as $total=0, write $total=$total+ ($order*$duration) inside loop

Upvotes: 4

Alaksandar Jesus Gene
Alaksandar Jesus Gene

Reputation: 6887

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

?> 

Upvotes: 2

Related Questions