jose
jose

Reputation: 1

Conditional field color

I would like to assign field colors like to the field "status". if the mysql filed is "yes" then it should be green, if "no" then it should be red. Who can assist? Many thanks in advance. below you will see my code:

$query = "SELECT * FROM members";   
$result = mysql_query($query);     
while (list($id,$name,$status) = mysql_fetch_row($result))
{ 
  echo("<tr><td>$name</td><td>$status</td></tr>\n"); 
}

Upvotes: 0

Views: 297

Answers (3)

Prafulla Kumar Sahu
Prafulla Kumar Sahu

Reputation: 9691

Considering $status is only yes or no, it should be treated as Boolean value. I assume this is an Boolean value.

$query = "SELECT * FROM members";   
$result = mysql_query($query);     
while (list($id,$name,$status) = mysql_fetch_row($result))
{ 
if($status){
      echo("<tr style='color:green'><td>$name</td><td>$status</td></tr>\n"); 
  } else {
      echo("<tr  style='color:red' ><td>$name</td><td>$status</td></tr>\n"); 
  }
}

Considering it to be Boolean we can modify Sougata's code to be like .

echo("<tr style='color:" 
. ($status ? 'red' : 'green') 
. "'><td>$name</td><td>$status</td></tr>\n");

You should also use mysqli or PDO as mysql_* are deprecated.

Upvotes: 1

devpro
devpro

Reputation: 16117

Stop using mysql_* extension its deprecated and close in PHP 7, use mysqli_* or PDO.

Here is the complete example of your code by using MYSQLi Object Oriented:

<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

$sql = "SELECT * FROM members";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {
        if($row['status'] == 'YES'){
        ?>
            <tr><td style="color:green;"><?=$row['name']?></td><td style="color:green;"><?=$row['status']?></td></tr>
        <?php   
        }
        else{
        ?>
            <tr><td style="color:red;"><?=$row['name']?></td><td style="color:red;"><?=$row['status']?></td></tr>
        <?php   
        }
    }    
} 
else 
{
    echo "0 results";
}
$conn->close();
?>

You just need to add check inside the while loop if status is YES use green color else red color

Upvotes: 1

Sougata Bose
Sougata Bose

Reputation: 31749

You can try -

echo("<tr style='color:" 
. (($status=='no') ? 'red' : 'green') 
. "'><td>$name</td><td>$status</td></tr>\n");

or also can do using an array of colors -

$colors= array('yes' => 'green', 'no' => 'red');
echo("<tr style='color:" 
. $colors[$status] 
. "'><td>$name</td><td>$status</td></tr>\n");

Upvotes: 4

Related Questions