2009-12-30 45 views
1

我正在使用生成的ID打印圖像。然而,我想要做一個檢查,看看是否存在圖像,如果它不打印無image.jpg的,而不是...if語句在一行上如果poss

<img src="phpThumb/phpThumb.php?src=../public/images/'.$row["id"].'/th.jpg&w=162" alt="" width="162" /> 

這將是巨大的,如果這可以保持在一行是可能的。任何幫助,將不勝感激。

回答

3

Kristopher艾夫斯說什麼,和file_exists

http://en.wikipedia.org/wiki/Ternary_operation

您可以通過做

echo (file_exists("/path/file/name/here") ? "web/path/goes/here" : "no_image.jpg") 

順便說一句,你的代碼片段不太可能工作,因爲你似乎o結合純HTML輸出和PHP,而不把PHP放入<? ?>

+0

它被封裝在php中但感謝您的提示... – Andy

2

哇,這個問題被提出並回答了很多:

<img src="<?php ($row['id'] != 0) ? "../public/{$row['id']}.jpeg" : 'no_image.jpg'; ?> > 
+0

我想他可能一直在問如何檢查圖像是否可用。 –

+0

是的,但那也是有用的:) – Andy

+0

哦,的確,我在自動模式下有點嘿嘿 –

3

我的建議實際上是從html標籤本身抽象出決策制定,在一個單獨的php邏輯塊中輸出html ...在這裏是一個簡短的例子,假設您沒有使用模板引擎或MVC框架。

<?php 
$filename = 'th.jpg'; 
$filePath = '/public/images/' . $row['id'] '/'; 
$webPath = '/images/' . $row['id'] . '/'; 
//Logic to get the row id etc 
if (!file_exists($filePath . $filename)) { 
    $filename ='no-image.jpg'; 
    $webPath = '/images/'; 
} 
?> 
<img src="<?php echo $webpath . $filename;?>" /> 
+0

我忘了解釋原因:P 在這種情況下,它將您的業務邏輯與您的演示邏輯分離開來,您可以稍後抽出它,如果您使用框架或決定重構代碼,並調出邏輯以確定從實際顯示它的邏輯中確定使用哪個源代碼路徑,並將穿插的php代碼保留在html中的最低限度。 –

+0

這是非常詳細的,謝謝。我爲未來的版本做這件事,我可以肯定地看到好處。再次感謝! – Andy

+0

非常好的一點。 –