1. Obtain a list of courses:
$dbh = new PDO('mysql:dbname=testdb;host=127.0.0.1', $user, $password);
$qry = $dbh->query("SELECT DISTINCT course_code FROM result [WHERE ...]");
$courses = $qry->fetchAll(PDO::FETCH_COLUMN, 0);
2. Loop over the results, constructing the above SQL:
mb_regex_encoding($charset);
$columns = str_replacemb_ereg_replace("`"'`', "``"'``', $courses);
$sql = "
SELECT student_id AS Matriculation, `".implode("`,`", $columns)."`, gp AS GP
FROM gp";
foreach ($columns as $column) $sql .= "
NATURAL JOIN (
SELECT student_id, grade AS `$column`
FROM result
WHERE course_code = ?
) AS `t$column`";
$sql .= "
WHERE level = ? AND semester = ?";
3. Execute the SQL, passing in the array of courses as parameters:
$qry = $dbh->prepare($sql);
$params = $courses;
array_push($params, $level, $semester);
$qry->execute($params);
4. Output the results:
echo "<table>";
echo "<tr>";
for ($i = 0; $i < $qry->columnCount(); $i++) {
$meta = $qry->getcolumnMeta($i);
echo "<th scope='col'>" . htmlentities($meta['name']) . "</th>";
}
echo "</tr>";
while ($row = $qry->fetch(PDO::FETCH_NUM)) {
echo "<tr>";
foreach ($row as $field) echo "<td>" . htmlentities($field) . "</td>"
echo "</tr>";
}
echo "</table>";