In this tutorial, you will learn how to make background colors of table rows alternate with a simple math equation.
Alternating background colors for a table with many rows helps the user follow information across the table easier, and quite possibly might make your site look a little more professional. In this example, I will use the variable $num to define how many rows will be in this table. I'm setting it to 20, but this of course can be determined by a mysql_numrows() function after requesting data from MySQL.
Now that I know the value of $num, I can start my loop. $i is the number of the row and it will increase by 1 for each new row printed.
PHP Code:
// Open the HTML table before the loop
echo "<table border=0 cellspacing=0 cellpadding=0>";
// define the loop parameters and start loop
for($i=0;$i<$num;$i++){
Now for the magic! The theory here is that for every even numbered row ($i), the background will print the first color, and every odd numbered row will print the second color.
PHP Code:
// define which colors for even and odd line numbers
if($i % 2 ==0)
{
$bgcolor='#f3f3f3';
}
else
{
$bgcolor='#e3e3e3';
}
// echo the table content with $bgcolor
echo "<tr bgcolor=$bgcolor><td> This is line number $i </td></tr>";
// close loop
}
// close table
echo "</table>";
?>
You should now be able to see your alternating background colors!
( Thanks Vivo for the Corrections! )