2011-07-15 183 views
0

這顯示從使用JOIN 查詢結果的PHP頁面(基於一個從教程和適合我的數據庫):引號和ifelse語句的PHP代碼 - 正確的語法?

<?php 
$connection = mysql_connect("localhost", "root", "PASSWORD") or die("Error connecting to database"); 
mysql_select_db("products", $connection); 
$result = mysql_query("SELECT * FROM buyers LEFT JOIN products USING (id);", $connection) or die("error querying database"); 
$i = 0; 
while($result_ar = mysql_fetch_assoc($result)){ 
?> 
<table> 
<tr <?php if($i%2 == 1){ echo "class='body2'"; }else{echo "class='body1'";}?>> 
<td> 
<?php echo $result_ar['buyer_name']; ?></td> 
<td> 
<?php echo $result_ar['manufacturer']; ?> 
</td> 
<td> 
<?php $result_ar['product_name'] = ($result_ar['product_name'] == '')? $result_ar['product_name'] : '"' . $result_ar['product_name'] . '"'; echo $result_ar['product_name']; ?> 
</td> 
</tr> 
</table> 
<?php 
$i+=1; 
} 
?> 

然而,這不是加入這是個問題,在這裏,但這個PHP代碼:

<?php $result_ar['product_name'] = ($result_ar['product_name'] == '')? $result_ar['product_name'] : '"' . $result_ar['product_name'] . '"'; echo $result_ar['product_name']; ?> 

我嘗試這樣做,它顯示以下(代碼完整的結果,在這個問題的開始):

John Zanussi "1500 Washing Machine" 
James Hotpoint "3000 Washing Machine" 
Simon Hotpoint 

我很驚訝它的工作,它只是一個測試聲明,看看代碼是否工作。

http://www.w3schools.com/php/php_if_else.asp是我的工具。

如果我是正確的,這意味着它會把任何陣列從引號PRODUCT_NAME列,但如果列是空白的,然後它會顯示引號。

只是檢查,看看我是否正確 - 試圖刷新我的PHP技能在這裏!

+0

與w3school在mysql的建議你會刷黑客技能也!開玩笑,但有時候這是一個不好的資源。 –

+0

是的w3schools是一個可憐的資源。不是一個理由,但這個問題downvote。 OP要求專家澄清三元運算符的功能。 –

回答

0

你是對的。在你的代碼三元操作等效於:

// If the product_name isn't empty, surround it in quotes. 
if (!empty($result_ar['product_name'])) 
{ 
    $result_ar['product_name'] = "\"{$result_ar['product_name']}\""; 
} 

使用三元操作在這裏是怎麼樣的混亂,因爲第一種情況(空值)仍然會導致空值。更經常地,您會看到相反的三元操作,用於爲空變量創建默認值。

在迴應變量的上下文中,可以將其縮短爲該表達式。在回顯變量之前,不需要重新分配變量。您可以回顯三元操作的結果。

// Based on your version... 
echo ($result_ar['product_name'] == '')? $result_ar['product_name'] : '"' . $result_ar['product_name'] . '"'; 

// Clearer version with the empty case last rather than first... 
echo !empty($result_ar['product_name']) ? "\"{$result_ar['product_name']}\"" : ""; 

要使用的三元操作指定一個類(可能有大膽的文字,例如),你可以使用類似這樣的表格單元格內:

<td class='<?php echo $result_ar['product_name'] == "Zanussi" ? "special_bold_class" : "regular_class";?>'> 

結果是:

<td class='special_bold_class'> 
+0

謝謝!這可以用於其他任何事情,例如如果價值等於Zanussi等,而不是其他製造商,則使文本爲粗體? – avenas8808

+0

@ avenas8808查看上面添加的示例。 –