Click to See Complete Forum and Search --> : alternate coloured rows in html table


Shears
07-22-2006, 07:18 PM
Part of a script i have that outputs a html table of data from an mysql table is as follows..
$query="SELECT * FROM stats";
$result=mysql_query($query);
$num=mysql_numrows($result);

$i=0;
while ($i < $num) {

$username=mysql_result($result,$i,"username");
$gold=mysql_result($result,$i,"gold");
$attack=mysql_result($result,$i,"attack");

Echo "
<tr>
<td>$username</td>
<td>$gold</td>
<td>$attack</td>
</tr>
";

$i++;
}
My problem is - for the html, i would like alternate rows to be in different colours (so they can be read more easily). Such as, first row - blue coloured, second row - light blue, third row - blue, fourth row - light blue. How should i go about doing this?

Thank you for any help :)

Shears

NogDog
07-22-2006, 07:40 PM
Within your output loop, do a modulus by 2 of your loop counter. If the result is 1, set it to one color, else set it to the other color:

$color = ($i % 2 ) ? '#0000CC' : '#3366FF';
Echo "
<tr style='color: $color'>
<td>$username</td>
<td>$gold</td>
<td>$attack</td>
</tr>
";

NogDog
07-22-2006, 07:43 PM
PS: to make the output HTML a bit more lightweight and easier to modify style-wise, instead of explicitly setting a color you could just assign a class to the TR element and specify the appearance in your CSS stylesheet.

Shears
07-22-2006, 09:30 PM
Thank you NogDog! That was exactly what i wanted :)

Shears