user979974
user979974

Reputation: 953

PHP - Add specific background color in table row

I have a table which has the following structure:

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

I would like to higlight cell in red when it is equal to 'QI' and in green color when it is equal to 'Validated'.

This is what I did, but it doesn't work. Can any anyone could help to fix my script?

My php script:

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


?>

Upvotes: 1

Views: 2845

Answers (2)

Sha7x
Sha7x

Reputation: 485

You need the style attribute and change the background-color

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

Upvotes: 1

James
James

Reputation: 1177

Try this code:

<?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>';
    }
}

Upvotes: 0

Related Questions