dongyan3853 2013-08-02 04:24
浏览 59
已采纳

如何使用CSS在PHP中使用if语句更改背景颜色

I'm looking to change the color of a cell in a table based on returns from a mySQL database.

song_order |   encore    
1          |     0             
2          |     0       
3          |     0       
4          |     0       
5          |     0       
6          |     0      
7          |     0       
8          |     1      
9          |     1       
10         |     1        
11         |     2       
12         |     2     

I'm echoing out the song_id cell but not the encore cell... How can I use the values in the encore cell to change the background of the song_id cell only?

 while($row = mysqli_fetch_array($show))
  {   

  echo "<tr>";  

   echo "<td style='padding: 10px; width:5px;'>" . $row['song_order'] ." </td>";
  echo "</tr>";
  }
  echo "</table>";

Would it be something like this? But how do I add these if values to 'song order'? I just don't know if this is right or how it needs to be modified...

while($row = mysqli_fetch_array($show))

{if ($row['encore'] == "0") $tdClass = 'mainset';

else if ($row['encore'] == "1") $tdClass = 'encore1';

else if ($row['encore'] == "2") $tdClass = 'encore2';

echo "";

echo "" . $row['song_order'] ." "; } echo "";

CSS
 .mainset {
    background-color:transparent;
 }
 .encore1 {
    background-color:pink;
 }
 .encore2 {
    background-color:blue;
 }

Am I on the right track, can someone help me with this code? Am I missing something and this already works?

  • 写回答

2条回答 默认 最新

  • dongshengli6384 2013-08-02 04:26
    关注

    Now put the class like

    echo "<tr>";  
        echo "<td style='padding: 10px; width:5px;' class='<?php echo $tdClass;?>'>" . $row['song_order'] ." </td>";
     echo "</tr>";
    

    And makesure that you put the right classes for the right css

    As per you comment try like this.Yor are echoing $tdClass in an echo which causes you conflict

     while($row = mysqli_fetch_array($show)) {
         if ($row['encore'] == "0") 
             $tdClass = 'mainset'; 
         else if ($row['encore'] == "1") 
             $tdClass = 'encore1'; 
         else if ($row['encore'] == "2") 
              $tdClass = 'encore2'; 
         echo "<tr>"; 
             echo "<td style='padding: 10px; width:5px;' class='".$tdClass."'>" . $row['song_order'] ." </td>";
         echo "</tr>";
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器