Wednesday, March 9, 2011

Alternating Table Row Colors

Many of website use this script to alternate their table row color that selected from mysql database, very useful and cool.


Overview


In this tutorial create 1 file
1. alternating_color.php

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



Step1:


Create table "test_mysql"



{code type=codetype}

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`
--


{/code}

{code type=codetype}

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');


{/code}

Step2:


Create file alternating_color.php



View In Browser


|---|--------------------- code --------------------|---|


{code type=codetype}

<?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();
?>


{/code}

1 comment: