在PHP MySQL动态表中更改行颜色的最佳方法是什么?

时间:2015-11-25 08:47:21

标签: php

我将MySQL数据库结果插入HTML表格,之后我尝试使用两种颜色更改行颜色

  

例如,如果第1行有红色,则第2行有黄色,第3行有   红色像智慧..

最好的方法是什么,我使用 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>

4 个答案:

答案 0 :(得分:2)

可以通过CSS

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

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

答案 1 :(得分:1)

包含css

self.item_logo = [self valueFromJSONWithKeyArray:event withKeyArray:@[@"categories",@"bikes",@"wheels",@"model",@"badge_uri"]];

替换表格标签
- (id) valueFromJSONWithKeyArray:(id)json withKeyArray:(NSArray *)keyArray
{
    for (NSString * keyString in keyArray)
    {
        if ([json[keyString] isKindOfClass:[NSObject class]])
        {
            json = json[keyString]; // go down a level
        }
        else
        {
            return nil; // we didn't find this key
        }
    }  
    return json; // We successfully found all the keys, return the object
}

答案 2 :(得分:1)

您应该使用类.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>

答案 3 :(得分:1)

你可以让它完全不使用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 */
   } 

顺便说一下,在界面中显示数据的非常糟糕的方法是从DB获取它并在视图中显示它(混合到输出缓冲区)的混合过程。这段代码看起来像是来自PHP3的旧丑陋血腥书籍的训练示例片段。它需要分离2个进程:首先从DB获取所有数据,然后将其放入带有外观的输出中。