Jump to content

Adding sql result numbers


Canman2005

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
Link to comment
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
Link to comment
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
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

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.