Home > Software design >  How to change the cell color of HTML table according to a threshold
How to change the cell color of HTML table according to a threshold

Time:06-17

I have a mysql query as below in my php page,

$query = "
select table_date as Date,vals as Value from usertable.table1 group by table_date;";

I am fetching data to columns from below method.

$result=mysqli_query($conn,$query);
while ($row = $result -> fetch_assoc())
{
    $q2Date .= '<td style="text-align:center"><b>'.$row['Date'].'</td>';
    $q2Value .= '<td style="text-align:center">'.$row['Value'].'</td>';
    $row['Date']  ;   
}

Then I am using $body variable as below to show them in a html table.

$body.= '
    <table style="top: 15px; left:10px; " border=1>

        <tbody>
            <caption style="color: rgb(241, 239, 243);background: rgb(1, 32, 65); ">Total Value</caption>
            <tr>
                <td style="text-align:center"><b>Date</td>'.$q2Date  .'
            </tr>
            <tr>
                <td style="text-align:center"><b>Value</td>'.$q2Value .'
            </tr>
        </tbody>
    </table>
';

From above method I could get the output as below,

enter image description here

Now I need to check each cell and change its color if it differs more than 25% from average value(lets say 250). Then the output should show as follows,

enter image description here

What changes to be done in my original code? Do I need to change my query as well? or HTML or both?

CodePudding user response:

check if value is greater than 250 then set background color style:

<?php
$result=mysqli_query($conn,$query);
while ($row = $result -> fetch_assoc())
{
    $q2Date .= '<td style="text-align:center"><b>'.$row['Date'].'</td>';
    if($row['Value'] >= 250)
        $q2Value .= '<td style="text-align:center;background-color:red;">'.$row['Value'].'</td>';
    else
        $q2Value .= '<td style="text-align:center;">'.$row['Value'].'</td>';
    $row['Date']  ;   
}

CodePudding user response:

its so simple to create a class in CSS let's say lessCell

.lessCell{
background:red;
}

then check the value if it is true add the class to if it's not do nothing

$cls="";

$result=mysqli_query($conn,$query);
while ($row = $result -> fetch_assoc())
{
if(your_condition==true){
$cls='';
}else{
$cls=""
}
    $q2Date .= '<td '.$cls.' style="text-align:center"><b>'.$row['Date'].'</td>';
    $q2Value .= '<td style="text-align:center">'.$row['Value'].'</td>';
    $row['Date']  ;   
}
  • Related