Using alternating row colors in a PHP database application is a nice way to give the user some visual differentiation between multiple rows of results – and the best part is that it’s so damn easy.  I’m going to assume that you’re using CSS for formatting, but if you are still using HTML to set attributed like background colors in your database results out table (gasp!), you can still make this code work just as easily.  In this example, we are using the CSS elements resultline and resultlinealt, but you can name them whatever you like.

/* OUTSIDE of the SQL loop, set a zero value for the rowcolor
* variable, which is basically just our row counter.
$rowcolor = 0;

/* Set values for your two different CSS styles here */
$report_class = ($rowcolor % 2) ? 'resultline' : 'resultlinealt';

/* Loop through the database results and print out
* the table rows - this example query assums we have
* executed a query asking for the name and address within a
* given table */
while (list($name, $address) = mysql_fetch_row($resultt)){
echo '<tr><td class="'.$report_class.'">'.$name.'</td></tr>';


Previous post

PHP/mySQL Breadcrumb Trail

Next post

Page Numbering (with x results per page)



I’m a tech geek/dev/infosec-nerd/scuba diver/blacksmith/sword-fighter/crime fighter/ENTP/warcrafter/activist. I'm the CTO at Mass Mosaic and the CEO of Grokability, Inc. in San Diego, CA. Tweet at me @snipeyhead or read more...