Total the result of 2 queries

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
Alpal
Forum Commoner
Posts: 39
Joined: Mon Jul 26, 2010 4:08 am

Total the result of 2 queries

Post by Alpal »

Need to total results of 2 queries, have this, it works, but not sure if it is the correct way to do this?

Code: Select all

<?php
$result1 = mysql_query('SELECT SUM(inv_paid_amount) AS total_paid FROM inv_to'); 
$row1 = mysql_fetch_assoc($result1); 
$result2 = mysql_query('SELECT SUM(Paid)AS paid_member FROM members_fin'); 
$row2 = mysql_fetch_assoc($result2);
$sum = $row1['total_paid']+$row2['paid_member'];
echo "$ ".number_format($sum, 2);
?>
Thanks in advance for any assistance
User avatar
mecha_godzilla
Forum Contributor
Posts: 375
Joined: Wed Apr 14, 2010 4:45 pm
Location: UK

Re: Total the result of 2 queries

Post by mecha_godzilla »

Hi,

Even if the two tables are linked in some way, I don't think there's going to be any real advantage in trying to retrieve both totals in the same query so what you're doing is probably correct. However, if you're running this query very often, you could add a separate column to each table that you increment whenever any invoices are paid - this would mean that your script would only have to retrieve a single value, not sum the values of all invoices in the database each time.

HTH,

Mecha Godzilla
Post Reply