php td Alternate row colors

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
cjkeane
Forum Contributor
Posts: 217
Joined: Fri Jun 11, 2010 1:17 pm

php td Alternate row colors

Post by cjkeane »

I'm wondering how to go about specifying alternate row colour backgrounds (eg white first row, grey the second row, and alternating thereafter.

below is my partial php code td i'm using to output row data from a database. anyone have any ideas on how to modify it to include alternating bg row colors? thanks.

Code: Select all

<?php

if($result==true)
{ 
do 
	{ 
	echo "<tr>";
	echo '<td nowrap><a href="details.php?IDNumber=' . $result['IDNumber'] . '">' . $result['IDNumber'] . '</a></td>';
	echo '<td nowrap>' . $result['Beneficiary'] . '</td>';
	echo '<td nowrap>' . $result['CompanyBranch'] . '</td>';
	echo '<td nowrap>' . $result['CompanyName'] . '</td>';				
	echo '<td nowrap>' . $result['CompanyReferenceNumber'] . '</td>';
    echo "</tr>"; 
    }
	while($result = mysql_fetch_array($query));
}                
     // close table>
     echo "</table><hr>"; 
 
?>

danwguy
Forum Contributor
Posts: 256
Joined: Wed Nov 17, 2010 1:09 pm
Location: San Diego, CA

Re: php td Alternate row colors

Post by danwguy »

only thing that comes to mind is, if you have an ID field in your database, give the <tr> an id='".$row['ID']."' then define bg colors on your css
User avatar
CrowderSoup
Forum Newbie
Posts: 18
Joined: Thu Apr 21, 2011 2:56 pm
Location: Murray, UT

Re: php td Alternate row colors

Post by CrowderSoup »

Normally what I do is have two css classes name TableRowEven and TableRowOdd. Then before I enter the loop I'll set a variable like this:

Code: Select all

$TableRowClass = "TableRowEven";
From there I'll enter my loop, and before doing anything:

Code: Select all

if($TableRowClass == "TableRowEven")
   $TableRowClass == "TableRowOdd";
else
   $TableRowClass == "TableRowEven";
Doing this will alternate that variable between both CSS class names. Then you can use that variable to output what CSS class you want to use:

Code: Select all

echo '<td class="'.$TableRowClass.'">Table_Data</td>';
cjkeane
Forum Contributor
Posts: 217
Joined: Fri Jun 11, 2010 1:17 pm

Re: php td Alternate row colors

Post by cjkeane »

thanks for the reply. it helped me to figure it out!
Post Reply