我有一个只有1个产品图像的商店,可以查看商店库存,上传时使用相同的产品代码将图像名称保存在文件夹"product images"中。示例
添加一个新产品,产品代码是12345我选择了一个要上传的图像,它被保存在"产品图像"文件夹中作为12345.jpg
现在我显示库存列表中的图像,如
<img src="product-images/<?php echo $show['product_code'] ?>.jpg" width="200" height="200">
它工作正常,但现在如果产品没有任何图像,我会得到一个空图像,因为文件不存在。
所以我想做一些类似的事情
if image exist in folder "product-images" show else show image default.jpg
如何检查和执行此操作?
您首先需要检查图像是否像这样存在,然后设置值。类似于:
$imagePath = "product-images/".$show['product_code'].".jpg";
if(!file_exists($imagePath))
$show['product_code'] = "default";
当然,您需要在名为default.jpg 的产品图像文件夹中有一个默认图像
但也许更好的想法是这样做:
$imagePath = "product-images/".$show['product_code'].".jpg";
if(!file_exists($imagePath))
$imagePath = "product-images/default.jpg";
然后在html中只放:
<img src="<?php echo $imagePath ?>" width="200" height="200">