Alternating color rows in PHP loop

17,359

Solution 1

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>";

Solution 2

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++;
}
Share:
17,359
Arnold Porche Villaluz
Author by

Arnold Porche Villaluz

Updated on June 08, 2022

Comments

  • Arnold Porche Villaluz
    Arnold Porche Villaluz almost 2 years

    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!

  • Arnold Porche Villaluz
    Arnold Porche Villaluz over 12 years
    this works, BUT it only displays 2 rows. Currently, I have 3 rows in my DB.
  • cwallenpoole
    cwallenpoole over 12 years
    What happens when you do a select * from physicians?
  • cwallenpoole
    cwallenpoole over 12 years
    Because the mysql_fetch functions pretty much have to work or you have BIG problems.
  • Arnold Porche Villaluz
    Arnold Porche Villaluz over 12 years
    this is my query: $qPhysician = mysql_query("SELECT * FROM physicians ORDER BY lastName ASC, firstName ASC");
  • armandomiani
    armandomiani over 12 years
    You're welcome. But I think it`s not about giving a fish but a fishing rod. ;)