Tuesday, May 12, 2009

Alternating colors in MySQL tabel with PHP

This code changes the color of alternating rows of a database output. There is a difference in results if used with Firefox as opposed to IE. In the former, no white grid will be visible while in the latter, a white grid will be visible as shown below

 

<?php
$dbhost = 'localhost'; // choose as needed 
$dbuser = 'xxx';  // choose as needed 
$dbpass = 'yyyy';  // choose as needed 
$dbname = 'DVD';  // choose as needed 
$tablename = 'DVD';  //choose as needed

//Connect to server and select database
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die("No connection");
//mysql_connect($dbhost, $dbuser, $dbpass) or die("No Connection");
mysql_select_db($dbname);

//Do the SQL
$query=("SELECT * FROM $tablename  ORDER BY Titel ASC ")  or die (mysql_error());
$result=mysql_query($query);

//variables for the table
$count=1;

// for greyish table
$akleur1="#CCCCCC";
$akleur2="#C0C0C0";

// uncomment and use for colorfull table 
// $akleur1="#C6FF00";
// $akleur2="#FFC600";

$kleur=$akleur1;

//Table heading and loop
echo"<table border='0'><tbody>";
echo"<tr><td><b>Nr</b></td><td><b>Titel</b></td><td><b>Acteur</b></td><td><b>Jaar</b></td><td><b>Summary</b></td><td>IMDB</td></tr>";
while($row = mysql_fetch_array($result, MYSQL_ASSOC))
{

    echo "<tr bgcolor=$kleur><td>$count</td><td>{$row['Titel']}</td>" .
         "<td><em>{$row['Acteur']}</em></td>" .
         "<td>{$row['Jaar']}</td>" .
         "<td>{$row['Summary']}</td>" .
         "<td><a href='{$row['IMDB']}'>imdb</a><td></tr>";

$count=$count+1;

if($kleur==$akleur1){
$kleur=$akleur2;
}
else {
$kleur=$akleur1;
}
}
echo "</tbody></table>";

// Close database
echo mysql_error();
mysql_close($conn);
?>

No comments:

Post a Comment