Displaying MySQL data in HTML tables

When displaying data PHP and HTML tables work well together.

In firstmysqlpage.php replace the whole WHILE loop with this lot and then save it as mysqltabledisplay.php:

echo "<table>";
    echo "<tr>";
        echo "<th>Reference</th>
            <th>Title</th>
            <th>Artist</th>
            <th>Price</th>
            <th>Label</th>";
    echo "</tr>";
    while ($cdrow=mysql_fetch_array($cdresult)) {
        $cdReference=$cdrow[cdReference];
        $cdTitle=$cdrow[cdTitle];
        $cdArtist=$cdrow[cdArtist];
        $cdPrice=$cdrow[cdPrice];
        echo "<tr>";
        echo "<td>$cdReference</td>
                <td>$cdTitle</td>
                <td>$cdArtist</td>
                <td>$cdPrice</td>
                <td>$cdLabel</td>";
        echo "</tr>";        
    }
echo "</table>";
        

You may also need to change the SELECT query by adding the cdReference field as that may not be in the query any more.

The code sets up an HTML table with headings and then loops through the rows putting data in.

  1. the first ECHO statement opens an HTML table element and the last ECHO closes it
  2. the second ECHO statement starts a row
  3. the third has all of the headings for the table (note that you can lay the code out any way to help it make more sense - it won't affect the end result)
  4. the fourth closes the headings row
  5. the loop then gets each record from the server and displays that as a row in the table using echo
  6. The final line close the TABLE element
submit to reddit Delicious Tweet