【问题标题】:PHP - Add specific background color in table rowPHP - 在表格行中添加特定的背景颜色
【发布时间】:2016-05-28 20:33:44
【问题描述】:

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

+--------+---------+----------+
|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);


?>

【问题讨论】:

  • 您确定要在while 中使用foreach 吗?

标签: php mysql css highlight cells


【解决方案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>';
    }
}

【讨论】:

  • 感谢您的脚本,但它会为单元格着色,但存在问题。在输出中,显示结果时内容丢失。加上第一列,而不是显示 BRA1、BRA1,我有 QI,已验证。所以我想知道 if 和 elseif 语句是否没有任何问题。
  • 投反对票?我的回答与你的问题一致。你可以改进你的问题。
  • 它现在可以工作了,当它没有经过验证或 QI 时,我忘了输入另一个条件。在 elseif 之后,我添加了 else {echo "&lt;td&gt;$cell&lt;/td&gt;";}
【解决方案2】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多