How can I have an alternating color rows in my php loop?
$num = mysql_num_rows($qPhysician);
$i=0;
while($i < $num)
{
echo "<tr>";
echo "<td>" . mysql_result($qPhysician,$i,"lastName") . "</td>";
echo "<td>" . mysql_result($qPhysician,$i,"firstName") . "</td>";
echo "</tr>";
$i++;
}
I have to omit the "<" and ">" for both "tr" and "td" because it wasn't allowed in this question. :)
thanks!
What do you mean? Are you saying you want to echo it in a table that alternates rows?
$num = mysql_num_rows($qPhysician);
$i=0;
echo "<table>"
while($i < $num)
{
if ($i % 2 == 0){
echo "<tr class='style1'>";
}
else{
echo "<tr class='style2'>";
}
echo "<td>" . mysql_result($qPhysician,$i,"lastName") . "</td>";
echo "<td>" . mysql_result($qPhysician,$i,"firstName") . "</td>";
echo "</tr>";
$i++;
}
echo "</table>";
Continuing with the example here:
$query = mysql_query("SELECT lastName, firstName FROM physicians");
$i = 0;
while( $arr = mysql_fetch_assoc( $query ) )
{
// use modulus (%). It returns the remainder after division.
// in this case, $i % 2 will be 1 when $i is odd, 0 when even.
// this is the ternary operator.
// it means (if this)? do this: otherwise this
// (Remember 1 is true and 0 is false so odd rows will be the odd
// class, even rows the even class)
echo ($i % 2)?'<tr class="odd">':'<tr class="even">';
// Now, use array indexing.
echo "<td>" . $arr[ "lastName" ] . "</td>";
echo "<td>" . $arr[ "firstName" ] . "</td>";
echo "</tr>";
$i++;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With