Snipe.Net - Geeky Stuff
Twitter
Currently: @DrugCrazed we made ourselves a promise to go back every 10 years. We have not kept our promise :( in reply to DrugCrazed 2 hrs ago

Alternating Row Colors in PHP/mySQL

closeThis post was published 9 years 7 months 7 days ago. There is a chance that some APIs or software versions discussed have changed since this article was written.

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.

[source lang='php']
/* 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 ‘
‘.$name.’

‘;
$rowcolor++;
}
[/source]

Also check out:

If you think this article kicked ass, subscribe to the RSS feed or follow me on Twitter! Share with your friends, or leave a comment below (or better still, do both!) My entire concept of self-worth is in your hands, so that makes you kind of a big deal. Srsly.

This entry was posted on Wednesday, June 19th, 2002 at 11:05 am and is filed under PHP/mySQL. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.