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

如何使用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 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法
  • ¥15 组策略中的计算机配置策略无法下发
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)
  • ¥50 mac mini外接显示器 画质字体模糊