Toggle colors in table with PHP [duplicate]

3

I have a code that displays a table in the% list of registered%, and to embellish, the code causes it to display 1 in 1 by alternating the colors between white and gray.

  • COR -> White
  • COR -> Gray
  • COR -> White
  • COR -> Gray ...
  • How can I make a repeat structure of ID's do the same thing?

    <?php
       $sqln = mysql_query("SELECT * FROM post ORDER BY id DESC LIMIT ".$inicio.",".$max."");
       $num = mysql_num_rows($sqln);
       for($i = 0; $i < $num; $i++){
         $tituloP = @mysql_result($sqln, $i, "titulo");
         $n = $i + 1;
         $d = $i % 2;
         if($d == 0){$cor = "cinza";}else{$cor = "claro";}
         print '<tr class='.$cor.'><td> align="center">'.$tituloP.'</td><tr>';
       }
    
    ?>
    

    I do not know if it makes a difference, but now I'm using while .

    <?php
       $sqln = mysqli_query($conn, "SELECT * FROM post ORDER BY id DESC LIMIT ".$inicio.",".$max."");
       mysqli_close($conn);
       while($num_q = mysqli_fetch_array($sqln)){
          $tituloP = $num_q['titulo'];
          print '<tr class=' /*COR*/'><td align="center">'.$tituloP.'</td><tr>';
       }
    ?>
    
        
    asked by anonymous 29.07.2015 / 19:14

    2 answers

    6

    You can do the same, but you put a counter,

    $index = 0;   
    while(...) {
    
        if($index%2==0){ echo 'class="branco"'; }
        else { echo 'class="cinza"'; }
    
        $index++;
    }
    
        
    29.07.2015 / 19:20
    5

    You can only do this with CSS using the :nth-child() selector.

    Removing formatting routines from your PHP code makes it easy to read and maintain

    tr:nth-child(even) {
      background-color: #fff;
    }
    tr:nth-child(odd) {
      background-color: #999;
    }
    <table style="width:100%">
      <tr>
    	<th>Number</th>
    	<th>Name</th>
      </tr>
      <tr>
    	<td>1</td>
    	<td>Eve Jackson</td>
      </tr>
      <tr>
    	<td>2</td>
    	<td>John Doe</td>
      </tr>
      <tr>
    	<td>3</td>
    	<td>Adam Johnson</td>
      </tr>
    </table>
        
    29.07.2015 / 19:59