Home > OS >  how to change cell color depending on values in php
how to change cell color depending on values in php

Time:09-30

This is the table that I'm using for receiving the data, I want that the Balance 1 and 2 assign a 3 types of color (red, yellow and green) based on the values, for example; I want to assign that the color red has to be assign when the value is <= 0, yellow when >= 1 && <=5 and green when the value is > 5

EDIT(I dont want to add another to show the color without the data inserted)

                    <td><b><?php echo $row ['part_number'] ?></b></td>
                    <td><b><?php echo date("M d, Y | h:i:s a",strtotime($row['datet'])) ?></b></td>
                    <td><?php echo $row ['description'] ?></td>
                    <td><b><?php echo $row ['max_1'] ?></b></td>
                    <td><b><?php echo $row ['min_1'] ?></b></td>
                    <td><b><?php echo $row ['stock_1'] ?></b></td>
                    <td><b><?php echo $row ['balance_1'] ?></b></td>
                    <?php echo "<td style='background-color:".(($row['balance_1'] < 1000) ? '#FF0000;' : '#FFFF00')."'></td>"; ?>
                    <td><b><?php echo $row ['max_2'] ?></b></td>
                    <td><b><?php echo $row ['min_2'] ?></b></td>
                    <td><b><?php echo $row ['stock_2'] ?></b></td>
                    <td><b><?php echo $row ['balance_2'] ?></b></td>
                    <?php echo "<td style='background-color:".(($row['balance_2'] < 1000) ? '#FF0000;' : '#FFFF00')."'></td>"; ?>

CodePudding user response:

Just add a class on each case:

if ($row['balance_1'] <= 0) {
   <td ><b><?php echo $row ['balance_1'] ?></b></td>
} else if ($row['balance_1'] >= 1 && $row['balance_1'] <= 5) {
   <td ><b><?php echo $row ['balance_1'] ?></b></td>
} else if ($row['balance_1'] > 5) {
   <td ><b><?php echo $row ['balance_1'] ?></b></td>
}

And in your css:

.red {
   background-color: #FF0000
}
.yellow {
   background-color: #FFFF00;
}
.green {
   background-color: #00FF00;
}

CodePudding user response:

Instead of using echo to print the td, you can use it to just print the color in the style attribute based on some condition

In this example I'm using a div to showcase:

$balance = 1000;
<div style="background-color: <?php echo $balance > 1 ? '#FF0000;' : '#FFFF00;'?>">
    test
</div>

The div then looks like this: div

I hope this can guide you forward :)

  • Related