Toggle colors in table with PHP [duplicate]

Posted on

Question :

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?

       $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 .

       $sqln = mysqli_query($conn, "SELECT * FROM post ORDER BY id DESC LIMIT ".$inicio.",".$max."");
       while($num_q = mysqli_fetch_array($sqln)){
          $tituloP = $num_q['titulo'];
          print '<tr class=' /*COR*/'><td align="center">'.$tituloP.'</td><tr>';


    Answer :

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

    $index = 0;   
    while(...) {
        if($index%2==0){ echo 'class="branco"'; }
        else { echo 'class="cinza"'; }


    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%">
    	<td>Eve Jackson</td>
    	<td>John Doe</td>
    	<td>Adam Johnson</td>


    Leave a Reply

    Your email address will not be published. Required fields are marked *