I want to generate an HTML table and display records from MySQL tables as columns, not rows, like:

The week names are in table 'week' and each week record also contains the number of sessions for that week:
+---------+-----------+----------+-----------+
| week_pk | week_name | sessions | cohort_fk |
+---------+-----------+----------+-----------+
|       1 | Week 1    |        3 |         1 |
|       2 | Week 2    |        2 |         1 |
|       3 | Week 3    |        1 |         1 |
+---------+-----------+----------+-----------+
The cohort table is:
+-----------+-------------+-------------+-------------+
| cohort_pk | cohort_name | cohort_code | cohort_year |
+-----------+-------------+-------------+-------------+
|         1 | Some name   | MICR8976    |        2014 |
+-----------+-------------+-------------+-------------+ 
I found some code which generates records in a table as HTML table columns, OK (I'm sure this code could be improved...).
So, the question is how can I modify this code to generate the session columns in the HTML table for each week coloumn? For example, for the Week 1 column in the HTML table, the 3 session columns, and so on for the other week columns?
Any help towards a solution appreciated.
   $query = "SELECT * FROM cohort, week 
            WHERE week.cohort_fk = cohort.cohort_pk 
            AND cohort.cohort_year = '$year' 
            AND cohort.cohort_pk = '$cohort'";
   $result = mysql_query($query, $connection) or die(mysql_error());
    echo "<table width = 50% border = '1' cellspacing = '2' cellpadding = '0'>";
    $position = 1;
    while ($row = mysql_fetch_array($result)){
    if($position == 1){
        echo "<tr>";
        }
    echo " <td width='50px'>" . $row['week_name'] . "</td> ";
    if($position == 3){
        echo "</tr> "; 
        $position = 1;
        }else{ 
        $position++;
        }
    }
    $end = "";
    if($position != 1){
    for($z=(3-$position); $z>0; $z--){
    $end .= "<td></td>";
    }
    $end .= "</tr>";
    }
    echo $end."</table> ";
 
     
    