2014-05-21 50 views
0

我正在使用以下查詢,並且想根據我查詢的項目之一的值更改div顏色。在下面的代碼中,我試圖檢查mgap_accept的值。如果值爲1,那麼結果將輸出在不同的div,然後如果該值不是1.基於特定查詢值的不同行輸出

我做了一個IF?ELSE,bt我不確定是否有更好的方法。這裏是我的代碼:

$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 
} 
?> 

回答

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

「:」 - ternary operator

+0

感謝您的幫助;我需要刪除if/else嗎? – DataGuy

+0

是的。只留下一個塊。 – voodoo417

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> 
0

您將始終需要if else聲明。

但是你可以縮短代碼:

$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>