tags:

views:

64

answers:

3

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?

+2  A: 

Set a variable to true/false or a number and then back again during each iteration. Or use the modulus operator such as $i%2==0 in a while loop where $i is a number and use this condition in a ternary statement or something that sets the class value of the <tr>

http://stackoverflow.com/questions/399137/easiest-way-to-alternate-row-colors-in-php-html

$i = 0;
while ( $row = mysql_fetch_assoc($result) ) {
 echo '<tr class="' . ( ( $i %2 == 0 ) ? 'oneValue' : 'anotherValue' ) . '"><td>' . $row['something'] . '</td></tr>';
$i++;
}
meder
This is not a *reverse* while loop. ;)
Marcel Korpel
No it isn't - I just stated that. Better change my statement.
meder
+2  A: 
<?php 

$x++; 

$class = ($x%2 == 0)? '.whiteBackground': '.graybackground';

echo "<tr class='$class'>";

?>

It basically checks to see if $x is divisible evenly by 2. If it is, it is even.

P.S. if you haven't seen that style of if else query, it is called a ternary operator.

Aaron Harun
works like a charm.
Sam
A: 

Or you could just use CSS:

table tr:nth-child(odd) { background-color: #ccc; }

Jason Palmer