Senin, 23 Maret 2009

Alternating Table Row Background Colors Using PHP

Feb17 in Design & Coding by David Shaw
I have put together this tutorial to help you alternate the background colors of table rows. Alternating table row background colors it will make it easier for your website’s users to understand data in tables, as well as making your table look better.


We will be using loops to loop through the table rows, and check to see if they even or odd numbered. If they are even they will be given one background color and if they are odd they will be given another.

We are assuming that you have some basic knowledge of using loops in PHP, and an understanding of simple HTML syntax, if you dont have a idea about basic HTML syntax then have a look at our HTML Cheat Sheet.

The first thing that you will need to do is to create your table:

view plaincopy to clipboardprint?



Once you have your table you will need to add your PHP code between the ‘table’ tags.

For this example I am going to use a table with 10 rows. But you can adapt this so that it uses the mysql_numrows() function after requesting data from MySQL.

So we now need to define the number of rows we require and begin the loop:

view plaincopy to clipboardprint?

$num = 10;

// define and start loop
for($i=0;$i<$num;$i++){
In the above code we set the number of rows, we then started a for loop by setting the row number to ‘0′ ($i=0). We then set our parameter so while the row number is less than the number specified the loop continues ($i<$num). We then set the row number to increase by ‘1′ everytime the loop is run ($i++).

We will now move onto the meaty bit. The code works by setting every even numbered row to the first color and any odd numbered row to the second color.

The code looks like this:

view plaincopy to clipboardprint?
// if row number is even use first color, if it is odd use the second
if($i % 2 ==0)
{
$bgcolor='#ffffff';
}
else
{
$bgcolor='#000000';
}

// output the table row with the correct background color
echo " Row Number is $i ";

// close loop
}
?>
The code above sets the background colors and then outputs the table rows. You can use this to help the users experience when using tables on your website, and also looks alot better than having the same background color throughout.

The complete PHP code that goes between your ‘table’ tags to alternate table row background colors looks like this:

view plaincopy to clipboardprint?

$num = 10;

// define and start loop
for($i=0;$i<$num;$i++){

// if row number is even use first color, if it is odd use the second
if($i % 2 ==0)
{
$bgcolor='#ffffff';
}
else
{
$bgcolor='#000000';
}

// output the table row with the correct background color
echo " Row Number is $i ";

// close loop
}
?>
You can now use PHP to alternate table row background colors on your website.

Feel free to comment on this code below.

Tidak ada komentar: