Zend - The PHP Company




Tables

Add Code


Alternating row background colors when printing results from a database query  

Type: application
Added by: nova2
Entered: 22/03/2000
Last modified: 08/12/1999
Rating: *** (8 votes)
Views: 11118
This small bit of code is an effecient way of alternating colors in an HTML table when printing the results of a database query.


<html>
<head>
<style>
.td1 {
    font: bold 10pt Tahoma;
    background: #AAAAAA;
}
.td2 {
    font: bold 10pt Tahoma;
    background: #BBBBBB;
}
.trhead {
    font: bold 11pt Tahoma;
    background: #00689e;
    color: #FFFFFF;
}
</style>
</head>
<body>

<?
mysql_pconnect
("localhost""*****""*****") or die("error connecting to database"); 
mysql_select_db("events") or die("error selecting database");

$rs mysql_query("SELECT ID, Name, City, County, Date FROM events order by $listEvents ASC");
    
        
// create an array holding the classes you want to switch between  
    
$classes=array("td1","td2");
        
// a counter to keep track of which class is currently being used
    
$classifier=0;
    
$num mysql_num_rows($rs);
    
$i 0;
    
    echo 
"<TABLE style="borderdouble" width=650 align=center cellpadding=4 cellspacing=0>";
    echo 
"<tr class=trhead>";
    echo 
"<td width=35%>Event Name</td>";
    echo 
"<td width=20%>City</td>";
    echo 
"<td width=20%>County</td>";
    echo 
"<td width=20%>Date</td>";
    echo 
"<td width=5%>&nbsp;</td>";
    echo 
"</tr>";
    
    while (
$i $num):
    
$id mysql_result($rs,$i,"ID");
    
$name mysql_result($rs,$i,"Name");
    
$city mysql_result($rs,$i,"City");
    
$county mysql_result($rs,$i,"County");
    
$date mysql_result($rs,$i,"Date");
    
$name "<a href=details.php3?id=$id&mode=1>" $name "</a>";
    
// access the value in the array associated with the key equal to the counter and print it in the <tr> bg
    
echo "<tr class=" $classes[$classifier] .">";
    echo 
"<td>" $name "</td>";
    echo 
"<td>" $city .  "</td>";
    echo 
"<td>" $county "</td>";
    echo 
"<td>" date("M j, Y"$date) . "</td>";
    echo 
"<td><a href=Action.php3?id=$id&mode=2 title="Edit"><img src="edit.gif" border=0></a></td>";
    echo 
"</tr>";
    
    
$i++;
        
// increment the counter and mod it by 2 to effectively alternate between two numbers
    
$classifier=($classifier+1)%2;
    endwhile;
    break;
?>
</body>
</html>    


Usage Example


See the example


Rate This Script





Search



This Category All Categories