ButterDog
ButterDog

Reputation: 243

Get sum of each row added together in while loop

So I have a mysql table that contains an integer in each row. What I am trying to do is get the sum of the integers. Here is what I currently have that is working.

$cn = 0;
$sql = mysqli_query($con,"SELECT * FROM members WHERE member='$userid'");
while($row = mysqli_fetch_array($sql)) {
$i = $row['number'];

$cn = $cn + $i;
}

echo $cn;

So I make $cn equal zero then each time it goes through the loop it will add the number from the matching row.

Does anyone have a better idea on how to accomplish this? Thanks!

Upvotes: 0

Views: 45

Answers (2)

djot
djot

Reputation: 2947

You don't need to use PHP or here a loop for that, because your database can do the job for you.

$sql = mysqli_query($con,"SELECT sum(number) FROM members WHERE member='$userid'");

Upvotes: 2

anurupr
anurupr

Reputation: 2344

If you want the sum of the column number for each member with a particular user id

$sum = 0;
$sql = mysqli_query($con,"SELECT SUM(number) as number_total FROM members WHERE member='$userid'");

while($row = mysqli_fetch_array($sql)) {
      $sum = $row['number_total'];
}

$sum will have the total

Upvotes: 1

Related Questions