简体   繁体   中英

What is the best way to change row colors in PHP MySQL dynamic table?

I insert MySQL db result into HTML table, after that I am trying to change row colors using two colors,

for example if 1st row has red 2nd row has yellow again 3rd row has red like wise..

what is the best possible way to do that, I wrote PHP code using PHP modulus function, is there any easist way to do that thank you..

<?php
$result = mysqli_query($link, "SELECT * FROM example");
?>
<table>
    <tr> 
        <th>Name</th> 
        <th>Age</th> 
    </tr>
    <?php
    $i = 0;
    while ($row = mysqli_fetch_assoc($result)) {

        if ($i % 2 == 0) {
            $bgColor = ' style="background-color:#CCFFFF;" ';
        } else {
            $bgColor = ' style="background-color:#FFFF99;" ';
        }
        echo "<tr>";
            echo "<td $bgColor>";
            echo $row['name'];
            echo "</td>";

            echo "<td $bgColor>";
            echo $row['age'];
            echo "</td>";
        echo "</tr>";

        $i++;
    }
    ?>
</table>

It can be done via CSS

tr:nth-child(even) {background: yellow}
tr:nth-child(odd) {background: red}

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

include css

<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">

replace table tag with

<table class="table table-striped" >

Instead of inline styles you should use classes .red and .yellow.

<?php
$result = mysqli_query($link, 'SELECT * FROM example');
?>
<table>
    <tr> 
        <th>Name</th> 
        <th>Age</th> 
    </tr>
    <?php
    $i = 0;
    while ($row = mysqli_fetch_assoc($result)) {

        echo '<tr class="' . (($i % 2 == 0) ? 'red' : 'yellow') . '">';
            echo '<td>';
            echo $row['name'];
            echo '</td>';

            echo '<td>';
            echo $row['age'];
            echo '</td>';
        echo '</tr>';

        $i++;
    }
    ?>
</table>

You able to make it not using PHP at all. Just use CSS with :nth-child pseudo-class

   tr:nth-child(2n) {
    background: #f0f0f0; /* row background color */
   } 
   tr:nth-child(1) {
    background: #666; /* row background color */
    color: #fff; /* text color */
   } 

By the way, It's very bad way to show data in interface to mixing process of getting it from DB and showing it in view (putting to output buffer). This code looks like as an traning example fragment from old ugly bloody book for PHP3. It's reqired to separate 2 process: first getting ALL data from DB, and after that puting it into output with appearance.

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