在我的表中有一个名为 statusid 的列。如果此列的值为 1,则整行需要着色为黄色。如果值为 2,则它需要为红色。 0 只是默认的白色。
执行此操作的最佳方法是什么?
<div class="container-fluid">
<table id="table_id" class="cell-border order-column row-border hover compact" width="100%">
<thead>
<tr>
<th width="2%">ID</th>
<th width="6%">Debiteur</th>
<th width="10%">Klantnaam</th>
<th width="3%">Aantal Pallets</th>
<th width="3%">Totaal Gewicht</th>
<th width="30%">PB Nummers</th>
<th width="10%">Toevoegdatum</th>
<th width="1%">statusid</th>
</thead>
<tbody>
<!-- Fetch from db -->
<!-- Connect to db-->>
<?php
$conn = mysqli_connect("localhost","root","","export") or die("Error in Connection");
$query = mysqli_query($conn, "SELECT exportid, deb_nmr, cost_name, numb_pal, tot_weight, pb_s, date, statusid FROM export_tabel");
while ($result = mysqli_fetch_array($query)) {
echo "<tr>
<td>".$result['exportid']."</td>
<td>".$result['deb_nmr']."</td>
<td>".$result['cost_name']."</td>
<td>".$result['numb_pal']."</td>
<td>".$result['tot_weight']."</td>
<td>".$result['pb_s']."</td>
<td>".$result['date']."</td>
<td>".$result['statusid']."</td>
</tr>";
}
?>
</tbody>
</table>
</div>
最佳答案
最好使用 CSS 类完成此操作,这样以后您可以更轻松地重新配置颜色。
switch ((int) $result['statusid']) {
case 1:
$rowClass = "row-yellow";
break;
case 2:
$rowClass = "row-red";
break;
default:
$rowClass = "row-default";
}
echo "<tr class='".$rowClass."'>
然后在您的 CSS 中,定义几个类:
.row-yellow {
background-color: yellow;
}
.row-red {
background-color: red;
}
如果您使用的是框架并且有某种可用的 View 编辑器选项,您可以创建一个可以调用的方法并使它更清晰。可能看起来像:
echo "<tr class='".$view->getStatusColor($result['statusid'])."'>
我只是将其作为需要考虑的事情提出来,因为在 View 逻辑中删除 switch 语句很快就会变得困惑。
关于php - 通过 mysql 值更改表行颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43877170/