[英]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.