Displaying MySQL data in HTML tables with styles

By using CSS and PHP together MySQL data can be presented more attractively. Here are just two possibilities:

Alternating rows

In mysqltabledisplay.php or an external stylesheet for that page add a class:

.greybg {
    background-color:#CCCCCC;
}
        

Now amend the loop to alternate colours (changed lines are commented with ****). Insert the new line (the first one here) before the existing WHILE and then change the other two lines:

$rowclass="";    // ****
while ($cdrow=mysql_fetch_array($cdresult)) {
    $cdReference=$cdrow[cdReference];
    $cdTitle=$cdrow[cdTitle];
    $cdArtist=$cdrow[cdArtist];
    $cdPrice=$cdrow[cdPrice];
    echo "<tr $rowclass >";    //****
    echo "<td>$cdReference</td>
            <td>$cdTitle</td>
            <td>$cdArtist</td>
            <td>$cdPrice</td>
            <td>$cdLabel</td>";
    echo "</tr>";
    if ($rowclass=="") { $rowclass="class=\"greybg\";"; } else { $rowclass=""; }    //****
}
        

The variable $rowclass starts off empty. The first time through the loop that means no class is applied to the TR. The IF statement then changes the empty variable to hold a class attribute/value pair. Next time through the loop that appears in the TR opening tag applying the new style to that row. The IF then empties the variable for the next time through the loop.

Highlighting data

Sometimes you might want to highlight certain items in a table of records. Possibly urgent tasks, items on sale, players in an MMORPG who are alive and so on:

Again adapt the loop in mysqltabledisplay.php to highlight any CDs under £5 in price:

            
$rowclass="";
while ($cdrow=mysql_fetch_array($cdresult)) {
    $cdReference=$cdrow[cdReference];
    $cdTitle=$cdrow[cdTitle];
    $cdArtist=$cdrow[cdArtist];
    $cdPrice=$cdrow[cdPrice];
    if ($cdPrice<=5) {$highlightclass="style=\"color:red;\";";} else {$highlightclass="";}    // ****
    echo "<tr $rowclass $highlightclass >";    //****
    echo "<td>$cdReference</td>
            <td>$cdTitle</td>
            <td>$cdArtist</td>
            <td>$cdPrice</td>
            <td>$cdLabel</td>";
    echo "</tr>";
    if ($rowclass=="") { $rowclass="class=\"greybg\""; } else { $rowclass=""; }
}        
        

Try to understand the structure of these two and the escaping of quotes. This is very likely to give you trouble when you start doing your own code so if something doesn't work check the escaping and quotes first.

submit to reddit Delicious Tweet