phpSensei Posted September 18, 2007 Share Posted September 18, 2007 How do you make it so like the first background color of the row is red, then the next one is blue, then red, then blue, based on a bunch of items echo'ed from a db table. ?? Quote Link to comment https://forums.phpfreaks.com/topic/69819-solved-row-bg-change/ Share on other sites More sharing options...
Barand Posted September 18, 2007 Share Posted September 18, 2007 set up a $count variable and increment it each row. If it's odd, use color A otherwise use color B. $color = $count++%2 ? 'red' : 'blue'; Quote Link to comment https://forums.phpfreaks.com/topic/69819-solved-row-bg-change/#findComment-350733 Share on other sites More sharing options...
trq Posted September 18, 2007 Share Posted September 18, 2007 As an example..... <?php for ($i=0;$i<=10;$i++) { echo "<div " . ($i % 2) ? "class='red'>" : "class='blue'>"; } ?> Quote Link to comment https://forums.phpfreaks.com/topic/69819-solved-row-bg-change/#findComment-350736 Share on other sites More sharing options...
tjodolv Posted September 18, 2007 Share Posted September 18, 2007 edit: I see I was too slow and not so elegant, but if you want to understand what's happening "behind" the ternary operators used in the above examples, take a look at mine. It's basically the same, only longer... If you echo the table using a loop, all you need to do is add a counter and a check for whether the current number is odd or even, and apply a css class to the current row: <?php $sql = "SELECT * FROM table"; $result = mysql_query($sql, $connection); $i = 1; // this is the counter - make sure you set it _outside_ the loop! while ( $row = mysql_fetch_assoc($result) ) { if ($i % 2 = 0) { // we check to see if the counter is en even number. if so - blue background $style = "blue"; } else { // if it's not, the background becomes red $style = "red"; } echo "<tr style=\"background: $class\"><td>$row[]</td></tr>"; // print the row $i++; // make sure this addition happens _inside_ the loop! } ?> Quote Link to comment https://forums.phpfreaks.com/topic/69819-solved-row-bg-change/#findComment-350743 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.