Below is my Query:
$query = "
SELECT *
FROM Teacher t
INNER JOIN Session s ON t.TeacherId = s.TeacherId
JOIN Grade_Report gr ON s.SessionId = gr.SessionId
WHERE
('".mysql_real_escape_string($sessionid)."' = '' OR gr.SessionId = '".mysql_real_escape_string($sessionid)."') ";
The results are stored in a table which code looks like this:
<table border='1'>
<tr>
<th>Session ID</th>
<th>Student Username</th>
<th>Student Name</th>
<th>Mark</th>
<th>Grade</th>
</tr>
<?php
while ($row = mysql_fetch_array($result)) {
echo "
<tr>
<td>{$row['SessionId']}</td>
<td>{$row['StudentUsername']}</td>
<td>{$row['StudentForename']} {$row['StudentSurname']}</td>
<td>{$row['Mark']}</td>
<td>{$row['Grade']}</td>
</tr>";
}
This query outputs 13 rows in the results which is fine when it selects all rows.
Now what happens is that I want the average mark for each session. So I include 'AVG(gr.Mark) as AvgMark'
in the query and include <td>{$row['AvgMark']}</td>
in the table. The Calculation it outputs is correct The problem is that the query now only outputs 1 row which is the top row of the query result. I understand this as AVG(gr.Mark)
only requires one row when outputted.
So my question is that except using SELECT
'AVG(gr.Mark) as AvgMark' in the query to find average marks of each session, is there a way I can workout average of each mark outside the query by using php so that the query output shows the 13 rows and is not affected and I can store the calculation of the average below the table rather than in the table?
The reason AVG returns one row is that it's an aggregate function, and without a GROUP BY clause operates on all rows.
Averages in PHP are just like averages everywhere else; total your values and divide by the number of samples. Hence, you can easily calculate the average in code by changing the code to:
<?php
$total = 0;
$count = 0;
while ($row = mysql_fetch_array($result)) {
$count++;
$total += $row['Mark'];
echo "
<tr>
<td>{$row['SessionId']}</td>
<td>{$row['StudentUsername']}</td>
<td>{$row['StudentForename']} {$row['StudentSurname']}</td>
<td>{$row['Mark']}</td>
<td>{$row['Grade']}</td>
</tr>";
}
$average = (int)($total/$count);
echo "<tr><td colspan=3></td><td>Average</td><td>$average</td></tr>".