PHP - 在表格行中添加特定的背景颜色

时间:2016-02-17 08:40:14

标签: php mysql css highlight cells

我有一个具有以下结构的表:

+--------+---------+----------+
|Col1    | Col2      | Col3   |
+-----------------------------+
| BRA1   | QI        | QI     |
+--------+-----------+--------+
| BRA2   | Validated | QI     |
+-----------------------------+

我希望在等于'QI'时将单元格高亮显示为红色,当等于'Validated'时,高亮显示为绿色。

这就是我所做的,但它不起作用。任何人都可以帮忙修复我的剧本吗?

我的php脚本:

<?php

$fields_num = mysqli_num_fields($result);
echo '<h1>Table:'.$tablename.'</h1>';
echo "<table border='1'><tr>";
// printing table headers
for($i=0; $i<$fields_num; $i++)
{
    $field = mysqli_fetch_fields($result);
echo '<td>'.$field[$i]->name.'</td>';
}
echo "</tr>\n";
// printing table rows
while($row = mysqli_fetch_row($result))
{
echo "<tr>";

    // $row is array... foreach( .. ) puts every element
    // of $row to $cell variable
    foreach($row as $cell)
    if($cell=="QI"){
        //echo "<td>$cell</td>";
        echo '<td BGCOLOR="#ff0000">'.$cell.'</td>';}
        elseif ($cell=="Validated") {echo '<td BGCOLOR="#3f9a0e">'.$cell.'</td>';} //Green color BGCOLOR="#3f9a0e"

    echo "</tr>\n";
}
mysqli_free_result($result);


?>

2 个答案:

答案 0 :(得分:1)

您需要样式属性并更改背景颜色

<td style="background-color: #ffffff">...</td>

答案 1 :(得分:-1)

试试这段代码:

<?php
...
$fields_num = mysqli_num_fields($result);
echo '<h1>Table:'.$tablename.'</h1>';
echo "<table border='1'><tr>";
// printing table headers
for($i=0; $i<$fields_num; $i++)
{
    $field = mysqli_fetch_fields($result);
echo '<td>'.$field[$i]->name.'</td>';
}
echo "</tr>\n";
// printing table rows
while($row = mysqli_fetch_row($result))
{
echo "<tr>";

    // $row is array... foreach( .. ) puts every element
    // of $row to $cell variable
foreach($row as $cell) {
    if($cell=="QI"){

            echo '<td style="background:#ff0000">'.$cell.'</td>';

    } elseif ($cell=="Validated") {

            echo '<td style="background:#3f9a0e">'.$cell.'</td>';
    }
}