website promotion banner
eturnkeys
Your Ad Here
Web Programming  Home Web Programming PHP Alternating Row Colors
rss

Alternating Row Colors

Author: Nathanael Mitchell More by this author
Browse Pages:  1  2  3 > >>


Alternating Row ColorsThere's two different ways this can be done. The first is by getting results from a mysql query, the second is going through the values of an array. I'll go over both. First the full files (ill break it up into two files, one using mysql, and one using an array)

First using mysql

<?

//db vars
$db_host = "host"; //change to your host
$db_user = "user"; //change to your user
$db_pass = "pass"; //change to your password
$db = "db"; //change to your db

//set a GLOBALS var to connect to the database
$GLOBALS['connection'] = mysql_connect($db_host, $db_user, $db_pass)
or die( "Unable to connect to SQL server");
mysql_select_db($db)
or die( "Unable to select database");

echo<<<EOF
<!DOCTYPE html PUBLIC " -//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd" >

<html>
<head>
<title>Title Here</title>
<style type="text/css">
td.RowOne {
background-color: #bfd9ff;
border: 1px solid #000000;
}
td.RowTwo {
background-color: #e8e8e8;
border: 1px solid #000000;
}
</style>
EOF;

//Set the Rows
$class1 = "RowOne";
$class2 = "RowTwo";
$class = $class1;

//Start the table
$table = "<table>";

//Get data from mysql table
$db_qur = "select * from TABLE";
$db_res = mysql_query($db_qur, $GLOBALS['connection']);
while($db_row = mysql_fetch_assoc($db_res)){
$table .= "<tr><td class="$class">$db_row[RowName]</td></tr>";
if($class == $class1){
$class = $class2;
} else {
$class = $class1;
}
}
$table .= "</table>";

//echo the table
echo $table;
?>

Next the file using an array

<?
echo<<<EOF
<!DOCTYPE html PUBLIC " -//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd" >

<html>
<head>
<title>Title Here</title>
<style type="text/css">
td.RowOne {
background-color: #bfd9ff;
border: 1px solid #000000;
}
td.RowTwo {
background-color: #e8e8e8;
border: 1px solid #000000;
}
</style>
EOF;

//Build the array
$array = array("value1", "value2", "value3", "value4", "value5");

//Set the Rows
$class1 = "RowOne";
$class2 = "RowTwo";
$class = $class1;

//Start the table
$table = "<table>";

//Loop through the array
foreach($array as $arr_value){
$table .= "<tr><td class="$class">$arr_value</td></tr>";
if($class == $class1){
$class = $class2;
} else {
$class = $class1;
}
}
$table .= "</table>";

//echo the table
echo $table;
?>

So theres the two different ways to do this. On the next pages I'll break everything down explaining whats going on.



print this page tell a friend subscribe to newsletter subscribe to rss
Rate this Material: Bad 1 2 3 4 5 Excellent
Browse Pages:  1  2  3 > >>

Add comments to "Alternating Row Colors"