How to give alternating table rows different background colors using PHP
        Posted  
        
            by Sam
        on Stack Overflow
        
        See other posts from Stack Overflow
        
            or by Sam
        
        
        
        Published on 2010-06-14T00:44:16Z
        Indexed on 
            2010/06/14
            0:52 UTC
        
        
        Read the original article
        Hit count: 334
        
php
I have a table of data that is generated dynamically based on the contents stored in a mysql database.
This is how my code looks:
<table border="1">
    <tr>
        <th>Name</th>
        <th>Description</th>
        <th>URL</th>
    </tr>
    <?php
        $query = mysql_query("SELECT * FROM categories");
        while ($row = mysql_fetch_assoc($query)) {
            $catName = $row['name'];
            $catDes = $row['description'];
            $catUrl = $row['url'];
            echo "<tr class=''>";
            echo "<td>$catName</td>";
            echo "<td>$catDes</td>";
            echo "<td>$catUrl</td>";
            echo "</tr>";
        }
    ?>
</table>
Now if the table was static, then I would just assign each alternating table row one of 2 styles in repeated order:
.whiteBackground { background-color: #fff; }
.grayBackground { background-color: #ccc; }
and that would be the end of that. However since the table rows are dynamically generated, how can I achieve this?
© Stack Overflow or respective owner