PHP make MySQL table rows alternate colours

Soldato
Joined
5 Dec 2003
Posts
2,716
Location
Glasgow
hey I am trying to display a table and make every other row a different colour, the code I am using is something akin to this:

if ($row % 2 == 1){
echo <tr style="background-color:green">
} else {
echo <tr style="background-color:white">
}

but the mod 2 doesn't seem to be working as every row is coming out the same colour. Anyone any ideas?
 
something like

PHP:
$x = 1;
while($row = mysql_fetch_assoc($result)) {
  echo '<tr style="background-color:' . $x % 2 == 1 ? 'green' : 'white' . '">';
  //blah blah
  $x++;
}
 
Last edited:
something like

PHP:
$x = 1;
while($row = mysql_fetch_assoc($result)) {
  echo '<tr style="background-color:' . $x % 2 = 1 ? 'green' : 'white' . '">';
  //blah blah
  $x++;
}

Ah thanks, that should do the trick. I think I tried a one-liner like that but I'm pretty hopeless with all the quotes and stuff.
 
If you want something thats much easier to read I use this method.

toggleColour = false

Loop
If (toggleColour) then colour = "#000" else colour = "#fff"

toggleColour = NOT toggleColour
Loop end
 
Or:

PHP:
$alt = false;
foreach ($rows as $row)
{
    echo '<tr style="background-color: ' . ($alt = !$alt) ? 'green' : 'white' . '">';
    // ...
    echo '</tr>';
}
 
Back
Top Bottom