Necesitas transponer los datos a un array intermedio antes de imprimir. Dos formas de hacerlo.
Método 1: obtiene cada fila e intercambia el índice de fila por el índice de columna:
<table> <tr><th>Subject</th><th>year1</th><th>year2</th><th>year3</th></tr> <?php $mysqli = new mysqli('localhost', 'user', 'pass', 'database'); $id = 1; $report = array(); $columnIndex = 0; $query = $mysqli->query("SELECT HTML, CSS, Js FROM term WHERE Stdid='$id'"); while ($results = $query->fetch_assoc()) { foreach ($results as $course => $score) { $report[$course][$columnIndex] = $score; } $columnIndex++; } foreach ($report as $course => $results) { ?> <tr> <th><?php echo $course; ?></th> <?php foreach ($results as $score) { ?> <th><?php echo $score; ?></th> <?php } ?> </tr> <?php } ?> </table>
Método 2: trae todo a un array de arrays y transponlo con array_map y una callback NULL (ver el ejemplo 4 del manual). Los nombres de los cursos van como primera fila para que sobrevivan a la transposición:
<table> <tr><th>Subject</th><th>year1</th><th>year2</th><th>year3</th></tr> <?php $mysqli = new mysqli('localhost', 'user', 'pass', 'database'); $id = 1; $data = array(array('HTML', 'CSS', 'Js')); $query = $mysqli->query("SELECT HTML, CSS, Js FROM term WHERE Stdid='$id'"); while ($row = $query->fetch_assoc()) { $data[] = $row; } $data = call_user_func_array('array_map', array_merge(array(NULL), $data)); ?> <?php foreach ($data as $row): ?> <tr> <?php foreach ($row as $value): ?> <th><?php echo $value ?></th> <?php endforeach; ?> </tr> <?php endforeach; ?> </table>
En ambas versiones, usa una sentencia preparada en lugar de interpolar $id en el SQL, y escapa la salida con htmlspecialchars().