How to give alternating table rows different background colors using PHP

前端 未结 6 496
面向向阳花
面向向阳花 2021-01-12 07:14

I have a table of data that is generated dynamically based on the contents stored in a mysql database.

This is how my code looks:

相关标签:
6条回答
  • 2021-01-12 07:23
    <?
    $color="1";
    while ($line = mysql_fetch_array($result)) {
      if($color==1){
        echo '<tr bgcolor="">';
        $color="2";
      } else { 
        echo '<tr bgcolor="#dcdcdc">';
        $color="1";
      }
      ?><td align="left" width="40"><a href=""></a><?= $line[name] ?></td>
    
    <?
    }
    ?>
    

    This is my working code !

    0 讨论(0)
  • 2021-01-12 07:24
    <?php 
    
    $x++; 
    
    $class = ($x%2 == 0)? 'whiteBackground': 'grayBackground';
    
    echo "<tr class='$class'>";
    
    ?>
    

    It basically checks to see if $x is divisible evenly by 2. If it is, it is even.

    P.S. if you haven't seen that style of if else query, it is called a ternary operator.

    0 讨论(0)
  • 2021-01-12 07:28

    This is how I did it. I declared a css class called "even" with all the styling i wanted. Then looped through the scenario. Hope it helps!

    <?php
        include 'connect.php';
        echo "<table id='hor-zebra'>";
        $i = 0;
        while($row = mysql_fetch_array($result))
        {
           if($i%2 == 0)
           {
              echo "<tr class='even'>";
              echo "<td>" . $row['something'] ." ". $row['something'] . "</td>";
              echo "</tr>";
           }
    
           else
           {
              echo "<tr>";
              echo "<td>" . $row['something'] ." ". $row['something'] . "</td>";
              echo "</tr>";
           }
           $i++;
        }
        echo "</table>";
    
        mysql_close($con);
    
      ?>
    
    0 讨论(0)
  • 2021-01-12 07:29

    Here is my working part ! `

     $i=1;
     while($row = mysqli_fetch_array($result)) {
     if($i%2==0)
     {
         echo '<tr bgcolor="#FFFF00">';
     }
     else
     {
         echo '<tr bgcolor="#99FFCC">';
     }
         $i++;
         echo "<td>" . $row['blah'] . "</td>";
         echo "<td>" . $row['blah_blah'] . "</td>";
         echo "</tr>";
    
     }
     echo "</table>";
    

    `

    0 讨论(0)
  • 2021-01-12 07:40

    Or you could just use CSS:

    table tr:nth-child(odd) { background-color: #ccc; }

    0 讨论(0)
  • 2021-01-12 07:43

    Set a variable to true/false or a number and then back again during each iteration. Or use the modulus operator such as $i%2==0 in a while loop where $i is a number and use this condition in a ternary statement or something that sets the class value of the <tr>

    Easiest way to alternate row colors in PHP/HTML?

    $i = 0;
    while ( $row = mysql_fetch_assoc($result) ) {
     echo '<tr class="' . ( ( $i %2 == 0 ) ? 'oneValue' : 'anotherValue' ) . '"><td>' . $row['something'] . '</td></tr>';
    $i++;
    }
    
    0 讨论(0)
提交回复
热议问题