添加SQL计数的值


Adding values of SQL count

我有一个表,它返回使用foreach的每个用户的一些SQL计数。我想要一个总数,它将所有的计数加起来。如有任何意见,不胜感激。

 $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>';

如果我真的理解你的问题,这很容易;只需在foreach循环之前为每个计数器声明一个变量,并用count值增加它。例如:

$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;
        ...
    }