Jump to content

[SOLVED] adding rows


ngreenwood6

Recommended Posts

I am trying to figure out how to add 2 rows from the database together. I have a database entry that is called amount. When i pull the information from the database I display it like this $row['amount']. I have more than one entry in the database and I want to be able to add them together. For example:

 

//make the connection
mysql_connect('localhost','user','pass');
mysql_select_db('database');

//make the query
$query = "SELECT * FROM table";

//perform the query
$results = mysql_query($query);

//get the contents
while($row = mysql_fetch_array($results))
{
echo $row['amount'];
echo "<br>";
}
?>

 

Now if I wanted to add them how would I add all the amounts to get a total. I have tried this:

 

$row_amount = $row['amount'];

$total = $row_amount + $row_amount;

echo $total;

 

That is not correct though because when i echo the total it gives me the same amount plus the same amount instead of adding all of the amounts. Any help is appreciated.

Link to comment
Share on other sites

I'd go for the MySQL SUM function too, however the php code you are using should be

 

$total = 0;
while($row = mysql_fetch_array($results))
{
    echo $row['amount'];
    echo "<br>";
    $total += $row['amount'];                // add row amount to total
}
echo "Total : $total";

 

Note:

$total += $row['amount'];

 

is a shorthand way of writing

 

$total = $total + $row['amount'];

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.