Forums

CC - totaling values of a field

tomluong 22 Nov, 2009
Hi all, I am struggling with CC. forgive my ignorance.
I am trying to total the values of a column based on user id.
Here is a simplified version of what I am trying to get done.
Say I have the following information in a table

user_id points
2 2
1 2
2 3
2 1
1 7

I want to display the results on the front end like
user_id total points
1 9
2 6

Is this possible?

TIA,
Tom
keywords: total totaling adding tallying sum sumation
nml375 22 Nov, 2009
Hi Tom,
Though it's been quite some time since I used ChronoConnectivity, I believe it's quite possible. You'll have to use some custom php-code to do the summary by hand though.

Something like this should do the trick:
Head:
<table>
 <tr>
  <th>user_id</th>
  <th>points</th>
 </tr><?
global $sum;
$sum = array();
?>

Body:
<?
global $sum;
if (array_key_exists($MyRow->user_id, $sum))
  $sum[$MyRow->user_id] += $MyRow->points;
else
  $sum[$MyRow->user_id] = $MyRow->points;
?>

Footer:
<?
global $sum;
ksort($sum);
foreach ($sum as $key => $val)
{
  echo " <tr><td>$key</td><td>$val</td></tr>";
}
?></table>


/Fredrik
tomluong 22 Nov, 2009
That worked beautifully, you're the greatest. my php/sql is lousy so trying to understand the logic of what you wrote is hard for me but after hours more of playing around with that code I managed to get it to show the username based off the user_id.

Here it is, if you know of a more elegant way to write it please feel free to give your input, I just was diving around the forums trying different combinations until I could get something to work.

In the Footer
<?
global $sum;
ksort($sum);


        $db =& JFactory::getDBO();

foreach ($sum as $key => $val)
{
        $query = "SELECT id, name, username FROM #__users WHERE id = '".$key."'";
        $db->setQuery($query);
        $row2 = $db->loadObject();
        echo $db->getErrorMsg();
        
echo " <tr><td>$row2->username</td><td>$val</td></tr>";
}
?></table>


Thanks again
This topic is locked and no more replies can be posted.