Easy Alternating Row Colors

So there are plenty of ways of displaying your MySQL rows with alternating colors. Here is a very simple (and probably well documented way) to make this work cleanly, but I get asked this often. The first step is to define the colors that you want to have alternate. I have chosen light colors so that black text will work with both.
$color1 = "#99FFFF";
$color2 = "#99FF99";
Then we need to define a baseline row count (hey...that's the name of this site sort of!)
$row_count = 0;
Next, we need to define the math that will figure out how to alternate the row colors
$altcolors = ($row_count % 2) ? $color1 : $color2);
Now, we can begin to work with the variable "$altcolors" to make the rows actually alternate.
// Connect to your MySQL database
require "path/to/your/database/connection/";

// Select the data
$select = mysql_query( "SELECT * FROM your_table_name ORDER BY column_name ASC" )
or die("SELECT Error: ".mysql_error());

// Begin grabbing the rows from your database
while ($row = mysql_fetch_array($select)) {

// Here's where we utilize the "$altcolors" variable
echo "<div style="background: $altcolors;"> ";

echo $row['SOME_COLUMN'];

echo "</div>";

echo $row_count++;

}
The next logical step is to apply this method to font colors, border colors, etc. For example, using two types of alternating colors...
$color1 = "#99FFFF";
$color2 = "#99FF99";
$fontcolor1 = "#444444";
$fontcolor2 = "#999999";
$row_count = 0;
$altcolors = ($row_count % 2) ? $color1 : $color2);
$altfontcolors = ($row_count % 2) ? $fontcolor1 : $fontcolor2);

//then your repeating element could have both color variables...

// Connect to your MySQL database
require "path/to/your/database/connection/";

// Select the data
$select = mysql_query( "SELECT * FROM your_table_name ORDER BY column_name ASC" )
or die("SELECT Error: ".mysql_error());

// Begin grabbing the rows from your database
while ($row = mysql_fetch_array($select)) {

// Here's where we utilize the "$altcolors" AND "$altfontcolors" variables
echo "<div style="background: $altcolors; font-color: $altfontcolors;">";

echo $row['SOME_COLUMN'];

echo "</div>";

echo $row_count++;
}
Post a comment





Real Time Web Analytics ^