簡體   English   中英

在 PHP MySQL 動態表中更改行顏色的最佳方法是什么?

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

我將 MySQL db 結果插入 HTML 表中,之后我嘗試使用兩種顏色更改行顏色,

例如,如果第一行有紅色,第二行又是黃色,第三行也有紅色。

最好的方法是什么,我使用PHP 模數函數編寫了 PHP 代碼,有什么簡單的方法可以做到這一點,謝謝..

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

它可以通過 CSS 完成

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

資料來源: http : //www.w3.org/Style/Examples/007/evenodd.en.html

包括CSS

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

將表標簽替換為

<table class="table table-striped" >

您應該使用類 .red 和 .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>

你可以讓它完全不使用 PHP。 只需將 CSS 與 :nth-child 偽類一起使用

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

順便說一句,在從數據庫獲取數據並在視圖中顯示(放入輸出緩沖區)的混合過程中,在界面中顯示數據是非常糟糕的方式。 這段代碼看起來像是 PHP3 的舊丑陋血腥書中的一個 traning 示例片段。 需要分離兩個過程:首先從數據庫中獲取所有數據,然后將其放入具有外觀的輸出中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM