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:
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> " ;
}
?>
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.