简体   繁体   中英

Adding values of SQL count

I have a table which echos back some SQL counts for each user using foreach. I want to have a total which will add up all the counts foreach. Any ideas would be appreciated.

 $students = get_course_students($course->id, 'lastname');    
    $toggle=0; 

if (!empty($students))  {
    foreach ($students as $student) {

$user=get_record('user','id',$student->id);

$atriskcountrecords = count_records_sql("SELECT COUNT(*) FROM mdl_ilp_tutorial WHERE template = 2 AND user = $user->id AND course = $course->id");
$personalcountrecords = count_records_sql("SELECT COUNT(*) FROM mdl_ilp_tutorial WHERE template = 1 AND user = $user->id AND course = $course->id");
$reportscountrecords = count_records_sql("SELECT COUNT(*) FROM mdl_ilp_reports WHERE user = $user->id AND course = $course->id");

echo '<tr class="r'.$toggle.'">
<td class="cell c'.$toggle.'" valign="top" nowrap="true" align="left">'.fullname($user).'</td>
<td class="cell c'.$toggle.'" valign="top" align="center">'.$atriskcountrecords.'</td>
<td class="cell c'.$toggle.'" valign="top" align="center">'.$personalcountrecords.'</td>
<td class="cell c'.$toggle.'" valign="top" align="center">'.$reportscountrecords.'</td>
</tr>';

if($toggle==0)$toggle=1;
else $toggle=0;         

}
}   

echo'<tr>
<td><strong>Totals</strong></td>
<td align="center"><strong>(TOTAL)</strong></td>
<td align="center"><strong>(TOTAL)</strong></td>
<td align="center"><strong>(TOTAL)</strong></td>
<td></td>
</tr>';


echo'</table>';

If I really understand your question, it's quite easy ; just declare a variable per counter before your foreach loop and increase it with count value. For example :

$atriskcountrecordsGlobal = 0;
if (!empty($students))  {
    foreach ($students as $student) {
        ...
        $atriskcountrecords = count_records_sql("SELECT COUNT(*) FROM mdl_ilp_tutorial WHERE template = 2 AND user = $user->id AND course = $course->id");
        $atriskcountrecordsGlobal += $atriskcountrecords;
        ...
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM