0

I have the following code that pulls a table from a mysql databse and turns it into a table in html.

$query = mysqli_query($link, "select * from timetable Where id = $id and subject != '' order by Day asc, Hour asc "  );
?>
<tr>
    <th>day</th>
    <th>hour</th>
    <th>subject</th>
</tr>
<?php
while ($row = mysqli_fetch_array($query)) {
    echo "<tr>";
    echo "<td>".$row['Day']."</td>";
    echo "<td>".$row['Hour']."</td>";
    echo "<td>".$row['Subject']."</td>";
    echo "</tr>";
}

?>

Im trying to make it so the day column is transposed to be along the top of the table as the first row.

Here is an example of a table

day hour subject
0   5   Maths
0   7   Maths
1   0   Maths
1   11  Physics
2   0   Physics
2   9   Maths
3   0   Physics
3   4   Maths
3   6   Physics
3   10  Maths
4   3   Maths
4   8   Physics
5   0   Maths
5   9   Physics
6   1   Maths
6   6   Physics

(note that I removed null values to make the table smaller for this question)

here is what I would like the table to look like

       Day  0     1     2      3     4     5     6 
  hour
     1   physics
     2
     3
     4                      maths
     5          ect 
     6
     7
     8
     9 
     10
     11
     12
elementzero23
  • 1,389
  • 2
  • 16
  • 38
  • "code that pulls a table from a mysql databse and turns it into a table in html" --> where is that code? – elementzero23 Feb 08 '17 at 10:32
  • http://stackoverflow.com/questions/14834290/mysql-query-to-dynamically-convert-rows-to-columns Refer this link. – Pathik Tailor Feb 08 '17 at 10:33
  • @elementzero23 ive added the code sry about that – Adam Anderson Feb 08 '17 at 10:38
  • The basic idea is two loops, one for the `` and one inside for the ``. You have to check everytime if the day-hour-combination has a value in the column "subject" and if so print that subject inside the ``. But SO is not a "please show me how to code this" site. – elementzero23 Feb 08 '17 at 10:43

1 Answers1

2

you can create this template firsly

<tr>
<td>Hours\Days</td>
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
</tr>

after that

<?php 
for($hour = 1;$hour < 13; $hour++){
    echo "<tr>";
    echo "<td>".$hour."</td>";  
    for($day = 0; $day < 7; $day++){
        while ($row = mysqli_fetch_array($query)) { 
            if($row['Day'] == $day && $row['Hour'] == hour)
                echo "<td>".$row['Subject']."</td>";
            else
                echo "<td></td>";
        }
    }   
    echo "</tr>"
}
?>

maybe u can write shorter code than me but its simple way.

vangoo
  • 91
  • 1
  • 12