2009-12-30 43 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

非常好的一点。 –