Jump to content

Archived

This topic is now archived and is closed to further replies.

Canman2005

Adding sql result numbers

Recommended Posts

Dear all

I have the following sql statement

[code]<?
$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>";
     }
?>[/code]

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

Share this post


Link to post
Share on other sites
I believe this would work:
[code]<?
$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.
[/code] :D

Share this post


Link to post
Share on other sites
Another way is to use MySql to get the total, assuming you don't want to print each number.
[code]<?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'];
?>[/code]

Ken

Share this post


Link to post
Share on other sites

×

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.