【问题标题】:MySql Table with different colors by valueMySql Table 按值具有不同的颜色
【发布时间】:2018-12-02 17:49:56
【问题描述】:

我正在使用 mysql 查询从数据库中获取数据。我所有的数据在表格中都显示得很好。现在我想按小于 2 或大于 3 的值对状态进行着色。 下面的代码不起作用。 需要帮助。

$result = mysqli_query($connect, $query);
if(mysqli_num_rows($result) > 0)
{
   $output .= '<div class="table-responsive">
      <table class="table table bordered">
         <tr>
            <th>name</th>
            <th>genre</th>
            <th>time</th>
            <th>status</th>
            <th>more...</th>
         </tr>';
?>
<?php
   function status_style($row) {
      if ($row < 2) return 'background-color: #ff0000'; //red
      if ($row > 3) return 'background-color: #33cc33'; //green
      return '';
   }
?>
<?php
   while($row = mysqli_fetch_array($result))
   {
      $output .= '
         <tr>
            <td>'.$row["name"].'</td>
            <td>'.$row["genre"].'</td>
            <td>'.$row["time"].'</td>
            <td>'.$row["status"].'</td>
            <td>'.$row["more"].'</td>
         </tr>
      ';
   }
   echo $output;
   {
      echo 'Data Not Found';
   }
?>

【问题讨论】:

    标签: php css mysqli colors html-table


    【解决方案1】:

    你可以试试这样的:

    <?php
    $result = mysqli_query($connect, $query);
    if(mysqli_num_rows($result) > 0)
    {
       $output .= '<div class="table-responsive">
          <table class="table table bordered">
             <tr>
                <th>name</th>
                <th>genre</th>
                <th>time</th>
                <th>status</th>
                <th>more...</th>
             </tr>';
       function status_style($row) {
          if ($row < 2) return $color = '#ff0000'; //red
          if ($row > 3) return $color = '#33cc33'; //green
          return $color = '';
       }
       while($row = mysqli_fetch_array($result))
       {
          $output .= '
             <tr style='"'background-color: '"' . $color . '"'>
                <td>'.$row["name"].'</td>
                <td>'.$row["genre"].'</td>
                <td>'.$row["time"].'</td>
                <td>'.$row["status"].'</td>
                <td>'.$row["more"].'</td>
             </tr>
          ';
       }
       echo $output;
       {
          echo 'Data Not Found';
       }
    

    你没有对背景颜色做任何事情。

    【讨论】:

      【解决方案2】:

      您已经创建了为行着色的函数,但在显示输出期间没有调用该函数。这就是它不起作用的原因。

      将您的 $output 变量更改为:

      $output .= '
          <tr>
              <td>'.$row["name"].'</td>
              <td>'.$row["genre"].'</td>
              <td>'.$row["time"].'</td>
              <td style="'.status_style($row["status"]).'">'.$row["status"].'</td>
              <td>'.$row["more"].'</td>
           </tr>
      ';
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-04-13
        • 2010-12-04
        • 1970-01-01
        • 2013-10-08
        • 1970-01-01
        • 1970-01-01
        • 2020-01-02
        相关资源
        最近更新 更多