Generate HTML table with alternating row styles

The following code shows you how to display a table of information with alternating rows having different visual appearance. The even-numbered rows in a table have a white background and odd-numbered rows have a gray background.

<style type="text/css">
.even-row {
    background: white;
}
.odd-row {
    background: gray;
}
</style>
<table>
<tr><th>ID</th><th>NAME</th></tr>
<?php
$styles = array('even-row','odd-row');
$db = new PDO('sqlite:altrowpeople.db');
foreach ($db->query('SELECT id, name FROM people') as $i => $row) { ?>
<tr class="<?php echo $styles[$i % 2]; ?>">
  <td><?php echo htmlentities($row['id']) ?></td>
  <td><?php echo htmlentities($row['name']) ?></td></tr>
<?php } ?>
</table>

Enjoyed this post? Share it!

 

Leave a comment

Your email address will not be published.