Cody Raspien - 11 months ago 68

PHP Question

I have a loop which extracts 2 numbers from a table and then calculates the total.

I want to find the final total (sum of all totals).

Is there a way to not use the DB to calculate the SUM but do it within the loop.

`while($row = $result->fetch_assoc()) {`

$total= $row["num1"] + $row["num2"];

}

How do I do this?

This is wrong:

`while($row = $result->fetch_assoc()) {`

$total= $row["num1"] + $row["num2"];

$total = $total + $total;

}

Answer

```
$total=0;
while($row = $result->fetch_assoc()) {
$sum= $row["num1"] + $row["num2"];
$total = $total + $sum;
}
```

Source (Stackoverflow)