0

I am using the following query and I would like to change div colors based on the value of one of my queried items. In the code below I am trying to check the value of mgap_accept. if the value is 1 then the results will be output in a different div then if the value is not 1.

I did it with an IF?ELSE, bt Im unsure if there is a better way. here is my code:

$result_cat = "SELECT mgap_accept,mgap_ska_id FROM mgap_orders WHERE mgap_ska_id = '$id'";
$stmt = $pdo->prepare($result_cat); 
$stmt->execute();
while($row_cat = $stmt->fetch(PDO::FETCH_ASSOC))
{

$id1=$row_cat['mgap_ska_id'];
$accept=$row_cat['mgap_accept'];
$growth=($total + $recovery);
if($accept == '1'){
?>
<div class="show">
<span class="namecustcoltype"><?php echo $id1;  ?></span>
<span class="namecusttype"><?php echo $accept;  ?></span>
<span class="growthcust">$<?php echo number_format($growth);  ?></span>
</div>
<?php
}else{
?>
<div class="showop">
<span class="namecustcoltype"><?php echo $id1;  ?></span>
<span class="namecusttype"><?php echo $accept;  ?></span>
<span class="growthcust">$<?php echo number_format($growth);  ?></span>
</div>
<?php 
}
?>

3 Answers 3

1
 <div class="<?php echo ($accept == '1')?'show':'showop';?>">

"?:" - ternary operator.

Sign up to request clarification or add additional context in comments.

2 Comments

thanks for the help; do I need to remove the if/else?
Yes. Leave only one block.
1
$result_cat = "SELECT mgap_accept,mgap_ska_id FROM mgap_orders WHERE mgap_ska_id = '$id'";
$stmt = $pdo->prepare($result_cat); 
$stmt->execute();
while($row_cat = $stmt->fetch(PDO::FETCH_ASSOC))
{

$id1=$row_cat['mgap_ska_id'];
$accept=$row_cat['mgap_accept'];
$growth=($total + $recovery);
$class = $accept == '1' ? "show" : "showop";
?>
<div class="<?=$class?>">
<span class="namecustcoltype"><?php echo $id1;  ?></span>
<span class="namecusttype"><?php echo $accept;  ?></span>
<span class="growthcust">$<?php echo number_format($growth);  ?></span>
</div>

Comments

0

You will always need an if else statement.

But you can shorten your code:

$accept == '1'? $class="show" : $class="showop;
?>
<div class="<?php echo $class; ?>">
<span class="namecustcoltype"><?php echo $id1;  ?></span>
<span class="namecusttype"><?php echo $accept;  ?></span>
<span class="growthcust">$<?php echo number_format($growth);  ?></span>
</div>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.