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.

Overview

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

Steps

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 ,
PRIMARY KEY (`id`)
) ;

Dumping data for table `test_mysql`

INSERT INTO `coding` VALUES (1, 'Billly', 'Blueton', 'bb5@testingmail.com');
INSERT INTO `coding` VALUES (2, 'Jame', 'Campbell', 'jame@somewhere.com');
INSERT INTO `coding` VALUES (3, 'Mark', 'Jackson', 'mark@testingmail.com');
INSERT INTO `coding` VALUES (4, 'Linda', 'Travor', 'lin65@testingmail.com');
INSERT INTO `coding` VALUES (5, 'Joey', 'Ford', 'fordloi@somewhere.com');
INSERT INTO `coding` VALUES (6, 'Siney', 'Gibson', 'gibn@testingmail.com');

Create file alternating_color.php


<?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";
$result=mysql_query($sql);

// Define $color=1

$color="1";

echo '<table width="400" border="1" align="center" cellpadding="2" cellspacing="0">';
while($rows=mysql_fetch_array($result)){

// If $color==1 table row color = #FFC600
if($color==1){
echo "<tr bgcolor='#FFC600'>
<td>".$rows['id']."</td><td>".$rows['name']."</td><td>".$rows['email']."</td>
</tr>";

// Set $color==2, for switching to other color
$color="2";
}

// When $color not equal 1, use this table row color
else {
echo '<tr bgcolor='#C6FF00'>
<td>".$rows['id']."</td><td>".$rows['name']."</td><td>".$rows['email']."</td>
</tr>';

// Set $color back to 1
$color="1";
}

}
echo '</table>';
mysql_close();
?>


Back