Sum on all columns fields of a db query

joomlamate

Member
I want to calculate (sum) all the selected column fields, of my db query:

here is what I have:

$userid = '{jos_customers___id}';

$db = JFactory::getDbo();

$query = $db->getQuery( true );
$query->select('donation_amount')
->from('jos_shop_order')
->where('school_id = ' . $db->quote($userid));

$db->setQuery($query);
$earnings = $db->loadColumn();
//print_r($earnings);

Ok so far, print_r gives me a string (?) of arrays with arrays with the fields I want to calculate for each row.
But, I am unable to get the sum for each array.

print_r output:
Array ( [0] => 15 ) Array ( [0] => 15 [1] => 25 ) Array ( ) Array ( [0] => ) Array ( [0] => 8 ) Array ( ) Array ( ) Array ( ) Array ( [0] => 5 [1] => 5 ) Array ( ) Array ( ) Array ( ) Array ( ) Array ( ) Array ( ) Array ( [0] => ) Array ( ) Array ( ) Array ( ) Array ( ) Array ( ) Array ( ) Array ( ) Array ( ) Array ( ) Array ( ) Array ( ) Array ( ) Array ( [0] => 5 [1] => [2] => 5 [3] => [4] => 5 [5] => )


Here how I try to calculate, but it always returns 0.
$total = 0;
foreach ($earnings as $earning) {

$sum = array_sum($earning);
$total += $sum;
}
return $total;
 
okay - I think I got it...
it looks like the calc field loops over each row...
so we have 1 array to sum for each row:

$total = array_sum($earnings);
return $total;

and it returns the sum of the array values for each row.

* I was struggling for some time to see the obvious. When I posted and return back to it, I simply just found the solution... and this is not the first this is happening... o_O
 
Where did you put this code, in a calculation element?
Where do you see this print_r output? in list view? (so it's one query/calculation per row and one print_r per row but all print_rs just displayed one after the other)

You ccould do the sum with the query:
$query->select('SUM(donation_amount)')
->from('jos_shop_order')
->where('school_id = ' . $db->quote($userid));

$db->setQuery($query);
$sum_in_one_row = $db->loadResult();
 
We are in need of some funding.
More details.

Thank you.

Members online

No members online now.
Back
Top