Home > Blockchain >  Change colour of element based on value
Change colour of element based on value

Time:01-06

I have code that shows the count of how many volunteers are in my database. How do I write a code that displays the colour of the echo to be red if the count/total is below 5?

 <?php
 $servername="localhost";
 $username="root";
 $password="";
 $dbname="schoolfair";
 $con=mysqli_connect($servername,$username,$password,$dbname);


$sql="SELECT count(idnumber) AS total FROM volunteers";
$result=mysqli_query($con,$sql);
$values=mysqli_fetch_assoc($result);
$num_rows=$values['total'];
echo "<tr> <td>" . $num_rows . "</td><td>" . $num_rows . "</td></td>";


?>

CodePudding user response:

Just use a class in the TD or TR tag based on the num_rows

$sql="SELECT count(idnumber) AS total FROM volunteers";
$result=mysqli_query($con,$sql);
$values=mysqli_fetch_assoc($result);
$num_rows=$values['total'];
$class = $num_rows >= 5 ? 'good' : 'bad' ;
echo "<tr><td class='$class'>$num_rows</td><td class='$class'>$num_rows</td></td>";

css

.good {
  background-color: green;
}

.bad{
  background-color: red;
}

CodePudding user response:

You can add some conditional styling. Alternatively, add a conditional class and declare the style in CSS. The code to add a class would be identical, except the $style = "style='color:red;'"; would be $style = "class='red-text'";

 <?php
 $servername="localhost";
 $username="root";
 $password="";
 $dbname="schoolfair";
 $con=mysqli_connect($servername,$username,$password,$dbname);


$sql="SELECT count(idnumber) AS total FROM volunteers";
$result=mysqli_query($con,$sql);
$values=mysqli_fetch_assoc($result);
$num_rows=$values['total'];


if($num_rows < 5) {
  $style = "style='color:red;'";
} else {
  $style = "";
}


echo "<tr> <td " . $style . ">" . $num_rows . "</td><td " . $style . ">" . $num_rows . "</td></td>";


?>
  •  Tags:  
  • Related