Add All Together - PHP & MySQL

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
micky007
Forum Newbie
Posts: 8
Joined: Mon Mar 14, 2011 1:43 pm

Add All Together - PHP & MySQL

Post by micky007 »

Hi Guys,

I need some advice please. In my database table called 'affleads' i have a row called Payout. Now below is the following MySQL code i am using on my PHP script:

Code: Select all

$query = "SELECT Payout FROM affleads WHERE AffID ='$affid'";
Now lets say there are 6 records matching the SQL query as the following:

[text]2.50
2.34
1.85
2.74
1.00
2.07[/text]

What PHP code would i use in order to get the values of Payout and then Add them all together and save the value to a variable?

Any help would be great and thank you in advance.

Thanks!
User avatar
Jonah Bron
DevNet Master
Posts: 2764
Joined: Thu Mar 15, 2007 6:28 pm
Location: Redding, California

Re: Add All Together - PHP & MySQL

Post by Jonah Bron »

Loop through the query results as usual, but add up the total.

Code: Select all

$total = 0;
while ($row = mysql_fetch_object($result)) {
    $total += $row->Payout;
}
User avatar
AbraCadaver
DevNet Master
Posts: 2572
Joined: Mon Feb 24, 2003 10:12 am
Location: The Republic of Texas
Contact:

Re: Add All Together - PHP & MySQL

Post by AbraCadaver »

Or just do it in the query:

Code: Select all

$query = "SELECT SUM(Payout) as Payout FROM affleads WHERE AffID ='$affid'";
mysql_function(): WARNING: This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQLextension should be used. See also MySQL: choosing an API guide and related FAQ for more information.
micky007
Forum Newbie
Posts: 8
Joined: Mon Mar 14, 2011 1:43 pm

Re: Add All Together - PHP & MySQL

Post by micky007 »

Hi,

Thank you for your reply and help, although I've just been thinking and have another problem. Below is what table looks like:

Image

What I'd like to do is do it so my PHP script will output the total number of records for each Program Name and output the Total Payout. So for example, going off the records above the output would be the following:
Nuffield Health - 3 - £7.50
I was thinking of using the DISTINCT method in SQL but then relised it wouldnt work to how i want it. Any help please guys would be great.

Thank you very much guys!
Post Reply