简体   繁体   中英

MySQLi PHP using Modulo to alternate row style

I have a fairly simple query in which I'd like to alternate styling of table rows. I have some logic mixed up in the while and for loop most likely but I'm stuck on how to correct it.

<table>
    <tr>
        <th>Title</th>
        <th>Author</th>
        <th>Media Type</th>
    </tr>               



<?php
   if($result = $link->query("SELECT * FROM smallgroup order by Author")){
     if($result->num_rows) {
        while($row = $result->fetch_object()){
         for($i=0;$i<10;$i++){
            if($i % 2)
            {
        ?>
        <tr style="background-color:#ccc;">
       <?php 
         }else{
        ?>
        <tr style="background-color:red;">
        <?php
         }
          }
         ?>
            <td>
            <?php echo $row->Title;?>&nbsp;&nbsp;&nbsp;
            </td>
            <td>
            <?php echo $row->Author;?>&nbsp;&nbsp;&nbsp;
            </td>
            <td>
            <?php echo $row->Media; ?>
            </td>
        </tr> 
   <?php     
            }   
       }
   }
  ?>
  </table>

Easiest way would be to use even and odd CSS property in your case

tr:nth-child(even) {background: #CCC;}
tr:nth-child(odd) {background: red;}

http://www.w3.org/Style/Examples/007/evenodd.en.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM