Semger
Semger

Reputation: 263

Conditional PHP styling based on variable value

I have some PHP code which executes and selects 10 rows from a SQL table. One column called result can hold the value of won, or loss.

if (mysqli_num_rows($result) > 0) {
    while($row = mysqli_fetch_assoc($result)) {
        echo "<div class = 'logrow'> <img src ='". $row["url"] ."'</img> <p class = 'logtext'>". $row["name"] ." bet $". $row["amount"] ." with a ".  $row["chance"] ."% chance and ". $row["result"] .". </p> </div>";
    }

How could I do something which would echo the values from each row as above but to echo a different statement for each row where the value of result is loss. For example to add an inline styling for the background colour.

So for example, say I have 10 rows found - 9 of these have $row["result"]as won, so they should be echoed as above. But 1 row has the value of $row["result"] as loss, a different echo should be applied. Perhaps with an inline style, or maybe with a variable inserted which hold this style.

I know this is very specific and may not be clear so thanks in advance.

Upvotes: 1

Views: 1882

Answers (2)

Aba
Aba

Reputation: 614

Based on the value in $row["result"] (won/loss) create a class and use it in the echo

css:
    .won{background-color::blue}
    .loss{background-color::red}

if (mysqli_num_rows($result) > 0) {
    while($row = mysqli_fetch_assoc($result)) {
        echo "<div class = 'logrow ". $row["result"] ."'> <img src ='". $row["url"] ."'</img> <p class = 'logtext'>". $row["name"] ." bet $". $row["amount"] ." with a ".  $row["chance"] ."% chance and ". $row["result"] .". </p> </div>";
    }

Upvotes: 3

Tismon Varghese
Tismon Varghese

Reputation: 869

Try this by changing class names.

<?php 
 $status = $row['result'];
 $classname = 'won';
 if($status == 0){
   $classname = 'fail';
 }
?>
<div class = 'logrow <?php echo $classname ?> '> <img src ='". $row["url"] ."'</img> <p class = 'logtext'>". $row["name"] ." bet $". $row["amount"] ." with a ".  $row["chance"] ."% chance and ". $row["result"] .". </p> </div>";

Now define classes for won and fail under style sheet.

<style type="text/css">
.won{ color: green; }
.fail{ color: red; }
</style>

Upvotes: 1

Related Questions