I am attempting to get the summation of a set of float values in a column of a table. I did a select query that pulls five sets of integers. A while function with a fetch_row is used to get the array. I use a foreach function to get the sum, however, the echo or printf does not give me one single variable. Instead I get an ever increasing value as each integer is added to the summation of the values before it. I have tried the array_sum, which doesn't work either. Please help! I have looked at every possible question in Stackoverflow.
<?php
//Check if at least one row is found
if($results2->num_rows > 0) {
//Loop through results and fetch as an array
$total = 0;
while($rows = $results2->fetch_row()){
foreach($rows as $sum)
$total += $sum;
printf($total.'<br/>');
}
}
?>
You're printing the total inside the loop, so you see all the subtotals. If you just want to see the final result, print it when the loop is done.
foreach ($rows as $sum) {
$total += $sum;
}
printf("%d<br/>", $total);
Also, when you use printf
, the first argument is a format string. The values come after, and they get substituted into the format.
You can also use array_sum
:
printf("%d<br/>", array_sum($rows));
Note that these are summing up all the columns in each row, not a single column in the whole table.