Switch colors in table with PHP

Asked

Viewed 1,433 times

3

I have a code that displays a table in the ID's registered, and to decorate, the code makes it display 1 in 1 alternating colors between white and gray.

  1. COLOR -> White
  2. COLOR -> Grey
  3. COLOR -> White
  4. COLOR -> Grey ...

How can I make a repeat structure while 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 don’t know if it makes a difference, only now I’m using mysqli.

<?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>';
   }
?>

2 answers

6


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

$index = 0;   
while(...) {

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

    $index++;
}

5

Can only be done with CSS using the selector :nth-child().

Remove 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>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.