当前位置: 动力学知识库 > 问答 > 编程问答 >

php - how to display data in tables with alternate row colour

问题描述:

I am trying to display data in tables using alternative colour schemes for rows.

I am using the code below to display to results.

<?php

while($row = mysql_fetch_array($sql)) {

echo "<tr> ";

echo "<td>" .$row[username] . "</td>";

echo "<td>" .$row[total] . "</td>";

echo "</tr> " ;

}

?>

I want to use this format for displaying data:

<tbody>

<tr class="alt"><td>Data</td><td>points</td></tr>

<tr><td>Data</td><td>points</td></tr>

<tr class="alt"><td>Data</td><td>points</td></tr>

<tr><td>Data</td><td>points</td></tr>

<tr class="alt"><td>Data</td><td>point</td></tr>

</tbody>

Kindly guide

网友答案:

Use css:

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

This fiddle shows how you can select even, odd, every n'th, or every n'th + x row to style it, with just CSS:

http://jsfiddle.net/zhd66arb/1/

网友答案:

Use modulo operator:

<?php
  $rowNum=0; 
  while($row = mysql_fetch_array($sql))  {
      echo "<tr ";
      if ($rowNum++ % 2 == 0) {
          echo 'class="alt"';
      }
       echo " >";
       echo "<td>" .$row[username] . "</td>";
     echo "<td>" .$row[total] . "</td>";
     echo "</tr> " ;
  }
网友答案:

try as shown below

<?php 

      $i = 0;
      while($row = mysql_fetch_array($sql))  {
      $class = "";
      if($i % 2 == 0)
          $class = "class='alt'";
      echo "<tr $class> ";
         echo "<td>" .$row[username] . "</td>";
         echo "<td>" .$row[total] . "</td>";
      echo "</tr> " ;
      $i++;
}

?>
网友答案:

Use a counter:

$i = 1
while($row = mysql_fetch_array($sql))
{
    echo "<tr" . (($i++%2) ? '' : ' class="alt"') . ">";
    echo "<td>" .$row[username] . "</td>";
    echo "<td>" .$row[total] . "</td>";
    echo "</tr> " ;
}
网友答案:

You'll want to use the modulus operator to obtain the remainder of dividing $rowNum by 2. Basically, for every row, add one to $rowNum, then check to see if it's even or odd. Also, make sure that you add quotes to username and total. Since you didn't enclose them in strings, they were being treated as constants.

<?php
$rowNum = 0;

while($row = mysql_fetch_array($sql))  {
    echo ($rowNum++ % 2 == 0) ? "<tr class=\"alt\">" : "<tr>";
    echo "<td>" .$row['username'] . "</td>";
    echo "<td>" .$row['total'] . "</td>";
    echo "</tr>";
}
?>
网友答案:

You can use a count variable to count the loop then use count%2 to get every other iteration.

<?php 

  $count = 0;  //The count variable
  while($row = mysql_fetch_array($sql))  {

     echo "<tr" // open the tag

       if($count%2 == 0) {
          echo "class='alt'"; // Ever other iteration, this will run
       }

     echo ">"; // close the tag
     echo "<td>" .$row[username] . "</td>";
     echo "<td>" .$row[total] . "</td>";
     echo "</tr> " ;
}

?>
分享给朋友:
您可能感兴趣的文章:
随机阅读: