PHP – MySQL Using MOD (%) Operator for Alternate Row Colors

I love how PHP and MySQL play so nicely together, it’s why I use them exclusively in all my software. With the release of HTML5 alternate row colors have become a lot easier with some simple css however PHP also offers a way to manipulate row colors with the use of the MOD (%) operator.


$get_data = "select * from table order by item";
$dbh = mysql_query($get_data) or die(mysql_error());
while($row = mysql_fetch_object($dbh)) {
$i++;
$color = ($i % 2) ? "#fffffff" : "#000000";
echo "

\n";
echo "Your Content Here";
echo "

\n";
}
?>

By using the code above, you are able to discern which row is even (%2) divisible by 2 with no remainder = “even” whereas (%2) with remainder = “odd”. This makes life easier when manipulating rows.

I’m also a huge fan of using Ternary or Short if statements

example:

$color = ($i % 2) ? "#fffffff" : "#000000";

This form of code looks cleaner and much easier to write as well…

$variable = (statement) ? "return if true" : "return if false";

Enjoy!

About Asia