Alternating table row colors

Hello Guys Welcome to Coding Gurus Online Portal ...!

We have gone through selecting data from the database and displayed in a table.But,in this tutorial we will go through displaying the data in table by changing the colors of table rows alternatively.Many websites use this script to decorate their table rows color that selected from mysql database,this article is very useful and cool.


In this article , we will create only 1 PHP file.
1. alternating_color.php


1. Create table coding in database codinggurus.
2. Create file alternating_color.php.

Create table coding

CREATE TABLE `coding` (
`id` int(4) NOT NULL auto_increment,
`name` varchar(65) NOT NULL ,
`lastname` varchar(65) NOT NULL ,
`email` varchar(65) NOT NULL ,
) ;

Dumping data for table `test_mysql`

INSERT INTO `coding` VALUES (1, 'Billly', 'Blueton', '');
INSERT INTO `coding` VALUES (2, 'Jame', 'Campbell', '');
INSERT INTO `coding` VALUES (3, 'Mark', 'Jackson', '');
INSERT INTO `coding` VALUES (4, 'Linda', 'Travor', '');
INSERT INTO `coding` VALUES (5, 'Joey', 'Ford', '');
INSERT INTO `coding` VALUES (6, 'Siney', 'Gibson', '');

Create file alternating_color.php

$host="localhost"; // Host name
$username="coding"; // Mysql username
$password="coding"; // Mysql password
$db_name="codinggurus"; // Database name
$tbl_name="coding"; // Table name

// Connect to server and select databse
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");

$sql="SELECT * FROM $tbl_name";

// Define $color=1


echo '<table width="400" border="1" align="center" cellpadding="2" cellspacing="0">';

// If $color==1 table row color = #FFC600
echo "<tr bgcolor='#FFC600'>

// Set $color==2, for switching to other color

// When $color not equal 1, use this table row color
else {
echo '<tr bgcolor='#C6FF00'>

// Set $color back to 1

echo '</table>';