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
