按 mysql 值更改 table 行颜色

Change table row color by mysql value

在我的 table 中,我有一个名为 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 class,这样以后您可以更轻松地重新配置颜色。

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 中定义一对 classes:

.row-yellow {
   background-color: yellow;
}
.row-red {
   background-color: red;
}

如果您使用的是框架并且有某种可用的视图编辑器选项,您可以创建一个可以调用的方法并使其更加清晰。可能看起来像:

echo "<tr class='".$view->getStatusColor($result['statusid'])."'>

我只是把它作为需要考虑的事情提出来,因为在视图逻辑中删除 switch 语句很快就会变得混乱。

好的,首先,您的 <thead> 行没有结尾 </tr>。其次,我认为如果为此使用数组会很有趣。另外,"best" 可以用多种方式定义,所以很难回答这个问题,有很多方法可以做到这一点,具体取决于您实际需要它的方式(例如,如果您需要在多个页面中使用它)。

$colors = ['white', 'yellow', 'red']; // or any other string, like a HEX color or a class name (which would change the code below, but do as you wish or prefer)
while ($result = mysqli_fetch_array($query)) {
    echo "<tr style='background-color: ".$colors[$result['statusid']].";'>
        <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>";
}