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
https://forums.phpfreaks.com/topic/127894-solved-adding-rows/
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
https://forums.phpfreaks.com/topic/127894-solved-adding-rows/#findComment-662151
Share on other sites

Archived

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

×
×
  • 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.