php - 通过 mysql 值更改表行颜色

标签 php mysql html-table row background-color

在我的表中有一个名为 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/

相关文章:

mysql - 复杂的 SQL 连接查询 - 获取最新行

mysql - 如何在mysql子查询中访问外列值?

Javascript 查询未将查询结果返回到 SharePoint 列表

html - 表格的 CSS 没有被应用,对吗?

javascript - 使用 JavaScript 可排序 html 整数表

php - 在第一个表插入时更新第二个表的 SQL 语法

javascript - 如何使用 post 方法根据添加的行表将数据保存在数组中?

PHP7构造函数类名

php - Symfony2 : Add method to an Entity

javascript - 如何在单击时获取表中行的第一个值?