How to Set Alternate Table Rows Color using PHP

How to set alternate table rows color using PHP:

Here, I want to show how to set alternate color to a table rows using PHP step by step.

Step 1: Firstly go to your PHPMYADMIN i.e. “http://localhost/phpmyadmin” and create a table employee in a database (let “test” database).

CREATE TABLE `employee` (
`empid` int(4) NOT NULL,
`empname` varchar(65) NOT NULL default '',
`esal` int(10) NOT NULL,
`edept` varchar(65) NOT NULL default '',
PRIMARY KEY (`empid`)
);

Step 2: Insert some records or data in the table employee

INSERT INTO `bikash`.`employee` (`empid`, `empname`, `esal`, `edept`) VALUES ('1001', 'Bikash Bhol', '20000', 'Account'), ('1002', 'Ajit Raka', '20000', 'Account'), ('1003', 'Sunil Mourya', '20000', 'Markating'), ('1004', 'Satya Prusty', '30000', 'Manager'), ('1005', 'Ram Rao', '25000', 'Sales');

Step3: Write the following program and save to C:/xampp/htdocs/ as emp_details.php .

<?php
$host="localhost"; // Host name
$username="root"; // Mysql username
$password=""; // Mysql password
$dbname="bikash"; // Database name
$tblname="employee"; // Table name
// Connect to server and select databse
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$dbname")or die("cannot select DB");
$sql="SELECT * FROM $tblname";
$result=mysql_query($sql);
// Define $color=1
$color="1";
echo '<h3 align = "center">Employee Details <hr /></h3>';
echo '<table width="400" border="1" align="center" cellpadding="2" cellspacing="0">';
while($rows=mysql_fetch_row($result)){
// If $color==1 table row color = #FFCCFF
if($color == 1){
echo "<tr bgcolor='#FFCCFF'><td>$rows[0]</td><td>$rows[1]</td><td>$rows[2]</td><td>$rows[3]</td></tr>";
// Set $color==2, for switching to other color
$color="2";
}
// When $color not equal 1, table row color = #FFC600
else {
echo "<tr bgcolor='#FFC600'><td>$rows[0]</td><td>$rows[1]</td><td>$rows[2]</td><td>$rows[3]</td></tr>";
// Set $color back to 1
$color="1";
}
}
echo '</table>';
mysql_close();
?>

Open your browser and enter http://localhost/emp_details.php and you will the output as follows:

alt_color.PNG