Alternating Table Rows with PHP

Alternating Table Rows with PHP

Using PHP and CSS , it’s very easy to create a report-style table with alternating colors on each row. This setup assumes a connection to a MySQL database (though any supported DBMS will work), and that you have already queried your database and are ready to work with the results in your php code.

CSS

.norm{
color:#fff;
background-color:#000;
}

.alt{
color:#000;
background-color:#fff;
}

PHP Code:

<?php

$style = 0;//switch to know which row we are on
echo '<table>';
while($row = mysql_fetch_array($query))
{
$name = $row['name'];//for each corresponding column name you wish to show
$add   =  $row['address'];
$email = $row['email'];

if($style == 0)
{
echo '<tr class="norm">';
echo '<td>'.$name.'</td>';
echo '<td>'.$add.'</td>';
echo '<td>'.$email.'</td>';
echo '</tr>';
$style++;
}else{
echo '<tr class="alt">';
echo '<td>'.$name.'</td>';
echo '<td>'.$add.'</td>';
echo '<td>'.$email.'</td>';
echo '</tr>';
$style--;
}
}
echo '</table>';

?>

That’s all, not much to it really.

Edit: It should be stated that this could be accomplished in a much more simple manner using the ternary operator to conditionally set the class, here is what that would look like:

<?php

$style = 'norm';//switch to know which row we are on
echo '<table>';
while($row = mysql_fetch_array($query))
{
$name = $row['name'];//for each corresponding column name you wish to show
$add   =  $row['address'];
$email = $row['email'];
echo '<tr class="'.$style.'"> ';
echo '<td>'.$name.'</td>';
echo '<td>'.$add.'</td>';
echo '<td>'.$email.'</td>';
echo '</tr>';
$style = ($style == 'norm') ? 'alt' : 'norm';
}
echo '</table>';

?>


About the Author

Rob McVey

I am a software developer/IT professional helping businesses save money through informed purchase consulting; website development and marketing; and process automation.