Alternate row color and style with PHP

As a programmer I work with databases as much as I sleep. When working with a list or large result set it can be very beneficial to alternate row color and or CSS style. This not only creates a visualy appealing effect, it also makes it alot easier as a user to interact with your result set. note: this little trick can be used anywhere you are looping information.

Heres an example without alternating rows

1
2
3
4
5
6
7
8
9
$sql = "SELECT * FROM fruits ORDER BY id";
$query = mysql_query($sql);					
while($result = mysql_fetch_assoc($query)) {
 
	echo "<div class='rName'>{$result['name']}</div>";
	echo "<div class='rDate'>{$result['date']}</div>";
	echo "<div class='rEdit'>{$result['edit']}</div>";
 
}

Which looks like this:

Alternating Row Styles
03/03/09
2mellow.com Data Testing
12/23/09
User Freindly Interface Techniques
01/31/09

 

Now the same example with alternating rows

1
2
3
4
5
6
7
8
9
10
11
12
13
$sql = "SELECT * FROM fruits ORDER BY id";
$query = mysql_query($sql);					
while($result = mysql_fetch_assoc($query)) {
 
	//heres our alternating hack
	if($css != "On"){ $css = "On"; }else{ $css = "Off"; }
 
	//append $css to the end of your style
	echo "<div class='rName{$css}'>{$result['name']}</div>";
	echo "<div class='rDate{$css}'>{$result['date']}</div>";
	echo "<div class='rEdit{$css}'>{$result['edit']}</div>";
 
}

Now I have a situation where my classes are either “on” or “off”. What you need to do now is create styles for each “toggle”. Heres the styles for my example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
/** ON STYLES **/
.rNameOn {
	padding:10px;
	float:left;
	width:300px;
	background-color:#E9EBEA;
	}
.rDateOn, .rEditOn {
	padding:10px;
	float:left;
	width:100px;
	background-color:#E9EBEA;
	}
/** OFF STYLES **/
.rNameOff {
	padding:10px;
	float:left;
	width:300px;
	background-color:#fff;
	}
.rDateOff, .rEditOff {
	padding:10px;
	float:left;
	width:100px;
	background-color:#fff;
	}

Our final result:

Alternating Row Styles
03/03/09
2mellow.com Data Testing
12/23/09
User Freindly Interface Techniques
01/31/09

 

3 Users Responded in " Alternate row color and style with PHP "

aleks said,  

this is a very useful tutorial… thanks for sharing!

Morley said,  

You’ve got a bug in your alternation code. It should be if ($css != “On”).

Brandon said,  

You are very correct, I had actually noticed it, but for some reason forgot to change, Thanks!!

Leave A Reply Here

  Username [*]

  Email Address [*]

  Website

Subscribes to this post comments updates

Please Note: All comments maybe under going moderation so there is no need to resubmit the comments. it will appeared when admin approved it, feel free to subscribes to the post comments rss to stay update