Alternating table row colors

Many of websites use this script to decorate their table rows color that selected from mysql database, very useful and cool.

Overview

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

Steps
1. Create table "test_mysql in database "test".
2. Create file alternating_color.php.

STEP1: Create table "test_mysql"

CREATE TABLE `test_mysql` (
`id` int(4) NOT NULL auto_increment,
`name` varchar(65) NOT NULL default '',
`lastname` varchar(65) NOT NULL default '',
`email` varchar(65) NOT NULL default '',
PRIMARY KEY (`id`)
) TYPE=MyISAM AUTO_INCREMENT=7 ;

--
-- Dumping data for table `test_mysql`
--

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

STEP2: Create file alternating_color.php

############### Code

<?php

$host="localhost"; // Host name
$username=""; // Mysql username
$password=""; // Mysql password
$db_name="test"; // Database name
$tbl_name="test_mysql"; // 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();
?>


Similar Post

PHP Counter script tutorial

Creates your own counter script. Using a basic knowledge of php + mysql script and keeps your visitors number to database for analysis.

Encrypting Password using md5() function

Using md5(); function to make your login system more secure