I am using PHP and I am iterating a table with a result array ... I want to add row color and alternate row color to it.... How to do so? Any suggestion...
To streamline your server code you could use javascript to highlight your rows and add mouse over/out handlers to the rows to do whatever you want.
Very easy to do with jquery and many examples.
<?php
include("BLL/index.php");
$objBLL = new BLL();
$result = $objBLL->SelectQuery();
$ID = $i;
$i = 1;
?>
<table border="1" width="50%">
<tr>
<td>ID</td>
<td>NAME</td>
<td>DESCRIPTION</td>
</tr>
<?php
while ($row = mysql_fetch_assoc($result)) {
if ($i % 2 != 0) {# An odd row
$rowColor = "orange";
echo '<tr bgcolor="' . $rowColor . '"><td >' . $row["ID"] . '</td><td >' . $row["Name"] . '</td><td >' . $row["Description"] . '</td></tr>' . "\r\n";
$i++;
}else{ # An even row
$rowColor = "green";
echo '<tr bgcolor="' . $rowColor . '"><td >' . $row["ID"] . '</td><td >' . $row["Name"] . '</td><td >' . $row["Description"] . '</td></tr>' . "\r\n";
$i++;
}
}
?>
</table>
Use modulo
<?php foreach($rackData as $key => $row) { ?>
<?php printf('<tr class="%s">', ($key % 2) ? 'odd' : 'even'); ?>
// ...
Then you can define CSS classes with the names .odd
and .even
and given them the background-color you want the rows to alternate with.
With modern browsers (read: not IE 8 or lower) you can also do it directly in CSS with the :nth-child pseudo class:
tr:nth-child(even) { background-color: #FFF; }
tr:nth-child(odd) { background-color: #EEE; }