What I want is the echo "<p>Average Mark: $average</p>"; to appear above the table rather than below the table. If I do this though the problem is that it won’t calculate the average as the echo is above the variable. But if I move the variable and with it the while loop above the whole table as I also need the while loop to select the $row[Mark]' field from a query as that is the field that is going to be averaged, it messes up the structure of the table. How can I display the $average, $total, $count etc variables and echo "<p>Average Mark: $average</p>"; above the table without messing up the table structure?
Below is current code and you can see the $count++; , $total += $row['Mark']; in the while loop and the $average variable and echo at the bottom.
$result = mysql_query($query);
mysql_close();
?>
<table border='1'>
<tr>
<th>Session ID</th>
<th>TeacherUsername</th>
<th>Teacher Name</th>
<th>Module Number</th>
<th>Module Name</th>
<th>Course ID</th>
<th>Course Name</th>
<th>Year</th>
<th>Student Username</th>
<th>Student Name</th>
<th>Mark</th>
<th>Grade</th>
</tr>
<?php
$total = 0;
$count = 0;
while ($row = mysql_fetch_array($result)) {
$count++;
$total += $row['Mark'];
echo "
<tr>
<td>{$row['SessionId']}</td>
<td>{$row['TeacherUsername']}</td>
<td>{$row['TeacherForename']} {$row['TeacherSurname']}</td>
<td>{$row['ModuleId']}</td>
<td>{$row['ModuleName']}</td>
<td>{$row['CourseId']}</td>
<td>{$row['CourseName']}</td>
<td>{$row['Year']}</td>
<td>{$row['StudentUsername']}</td>
<td>{$row['StudentForename']} {$row['StudentSurname']}</td>
<td>{$row['Mark']}</td>
<td>{$row['Grade']}</td>
</tr>";
}
?>
</table>
<?php
$average = (int)($total/$count);
echo "<p>Average Mark: $average</p>";
?>
Instead of echoing the rows , save them to a variable. Then echo the calcuated value before eching the variable you saved. Observe: