Home  >  Q&A  >  body text

Dynamically change HTML TD background color based on value using PHP

I'm trying to dynamically change the TD background color, but it's driving me crazy because I don't really know how to fix the code.

This is my code:

<td data-column="% Over 0.5 SH" style="background-color: <?php echo $backgroundColorOver05SH; ?>">
<?php 
if (($row['TotalMatch']) > 9){ 
$percover05sh = $row['OK_05sh'] / $row['TotalMatch'] * 100; 
echo sprintf("%.2f", $percover05sh);


if ($percover05sh > 80){
    $backgroundColorOver05SH = "green";
} elseif ($percover05sh >= 70 and $percover05sh <= 79.99  ){
    $backgroundColorOver05SH = "yellow";
} else {
    $backgroundColorOver05SH = "red";
}

I think I'm on the right track, but I can't find the right solution. Any suggestions? Thanks!

Edit: This code now works! This is my complete code:

<?php 
if (($row['TotalMatch']) > 9){ 
$percover05sh = $row['OK_05sh'] / $row['TotalMatch'] * 100; 

if ($percover05sh >= 80){
    $backgroundColorOver05SH = "green";
} elseif ($percover05sh >= 70 && $percover05sh < 80  ){
    $backgroundColorOver05SH = "yellow";
} else {
    $backgroundColorOver05SH = "red";
}

}else{
echo 'No Bet';
}     ?>
<td data-column="% Over 0.5 SH" style="background-color: <?php echo $backgroundColorOver05SH;?>;">
<?php
echo sprintf("%.2f", $percover05sh);    
?>
</td>

P粉295728625P粉295728625175 days ago263

reply all(2)I'll reply

  • P粉908643611

    P粉9086436112024-04-01 00:23:43

    In addition to changing the order in the code (as written in the question comments), I would also add a semicolon after the background color value echoed by PHP in the style attribute, which is

    reply
    0
  • P粉938936304

    P粉9389363042024-04-01 00:13:34

    So first:

     
     9){ 
    $percover05sh = $row['OK_05sh'] / $row['TotalMatch'] * 100; 
    echo sprintf("%.2f", $percover05sh);
    
    
    if ($percover05sh > 80){
        $backgroundColorOver05SH = "green";
    } elseif ($percover05sh >= 70 && $percover05sh < 80  ){
        $backgroundColorOver05SH = "yellow";
    } else {
        $backgroundColorOver05SH = "red";
    }
    ?>
    
     9){ 
    */
    }
    ?>
    

    If the color doesn't change, maybe it's set by a different CSS rule or script?

    reply
    0
  • Cancelreply