Jump to content


Photo

Adding sql result numbers


  • Please log in to reply
2 replies to this topic

#1 Canman2005

Canman2005
  • Members
  • PipPipPip
  • Advanced Member
  • 669 posts

Posted 22 April 2006 - 01:32 PM

Dear all

I have the following sql statement

<?
$sql ="SELECT * FROM log WHERE code = '".$_SESSION['code']."'";
$result = @mysql_query($sql,$connection) or die(mysql_error());

    while ($rows = mysql_fetch_array($result))
    {
    print "$rows[id]<br>";
     }
?>

Which is fine and currently produces the following

100
300
250
150
800

How can I get it to add up all these numbers and come up with the final number, it would look like

100+300+250+150+800

which would produce 1600

Any ideas?

Thanks in advance

Ed

#2 Tim

Tim
  • New Members
  • Pip
  • Newbie
  • 2 posts

Posted 22 April 2006 - 04:04 PM

I believe this would work:
<?
$sql ="SELECT * FROM log WHERE code = '".$_SESSION['code']."'";
$result = @mysql_query($sql,$connection) or die(mysql_error());
$sum = 0;
while ($rows = mysql_fetch_array($result))
{
    print "$rows[id]<br>";
    $sum += $rows['id']; //add this number to the sum.
}
?>
// $sum now equals 1600.
:D

#3 kenrbnsn

kenrbnsn
  • Staff Alumni
  • Advanced Member
  • 8,235 posts
  • LocationHillsborough, NJ, USA

Posted 22 April 2006 - 04:34 PM

Another way is to use MySql to get the total, assuming you don't want to print each number.
<?php
$sql ="SELECT sum(id) as total_id FROM log WHERE code = '".$_SESSION['code']."'";
$result = @mysql_query($sql,$connection) or die(mysql_error());
$row = mysql_fetch_array($result);
echo 'Total: ' . $row['total_id'];
?>

Ken





0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users