简体   繁体   中英

Change table row color based on value

I have a table that looks something like this:

ID     |     photo      |   ident     | status
------------------------------------------------
80     |    img/photo1  |   ACH3882   |   V
81     |    img/photo2  |   SHD8837   |   V
82     |    img/photo3  |   SFF4837   |   X
83     |    img/photo4  |   DLL3266   |   V

Is it possible to change the rows background color, depending on the value? So if status cell value is V, make yellow, and if X make green?

This is my table, and what I have tried:

<table class="blueTable" border="2" style= "background-color: #f9f9f9; color: #000000; margin: 0 auto;" >
  <thead style= "background-color: #FFFFFF">
    <tr>
      <th>Photo</th>
      <th>Ident</th>
      <th>Status</th>
      <th>Delete</th>
    </tr>
  </thead>
  <tbody>
    <?php
     if ($result = $link->query($query)) {
          $num_rows = 0;
          while ($row = $result->fetch_assoc()) {
              $num_rows++;
                 if($row['status'] == 'V') {
                      $style = 'style="background-color:#00FF00;';
                  }
                  
                  if($row['status'] == 'X') {
                      $style = 'style="background-color:#FF00FF;';
                  }
              echo
              "<tr>
              <td>{$row['photo']}</td>
              <td>{$row['ident']}</td>
              <td>{$row['status']}</td>
              <td><a href='delete.php?id={$row['id']};'>Delete</a></td>
              </tr>";
             
          }
          /*freeresultset*/
          $result->free();
      }
    ?>
  </tbody>
</table>

But somehow the background color does not change. Any suggestions?

You can use your status var as a class and add the colors for the classes in css like this

 .color-v { background-color: blue; }.color-x { background-color: green; }
 <table class="blueTable" border="2" style= "background-color: #f9f9f9; color: #000000; margin: 0 auto;" > <thead style= "background-color: #FFFFFF"> <tr> <th>Photo</th> <th>Ident</th> <th>Status</th> </tr> </thead> <tbody> <?php if ($result = $link->query($query)) { $num_rows = 0; while ($row = $result->fetch_assoc()) { $num_rows++; echo "<tr class='color-{$row['status']}'> <td>{$row['photo']}</td> <td>{$row['ident']}</td> <td>{$row['status']}</td> </tr>"; } /*freeresultset*/ $result->free(); }?> </tbody> </table>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM