2013-05-16 8 views
0

我有一個產品組合,每個人都有一個圖像,如果數據庫字段'圖像'是空的我正在加載一個通用圖像,但如果在某些情況下該字段有一個圖像值,但不存在我要使用通用的圖像過於文件中,我使用下面的代碼嘗試,但僅適用於空字段:如果空或破壞,添加通用圖像

<div class="wrapper"><a href="store.php?url=<?php echo $row->url ?>"><img src="images/stores/category/ 

<?php   
if (empty($row->image) or file_exists($row->image)==false) { 
    echo 'generic.jpg'; 
}else{     
    echo $row->imagen; }?>" alt="<?php echo $row->seo ?>"/></a></div>   
    </div> 
    <?php } ?> 

感謝您的時間!

+0

這是一個錯字'$按行> imagen畫質'? – elclanrs

+0

使用'is_file'而不是'file_exists'。如果路徑是目錄,最後一個也會返回true。 –

回答

0

好的代碼應該是這樣的:

注1:使用is_file檢查文件確實存在,並可用

注2:使用相對路徑從你的腳本文件,因爲該字段包含文件名

注3:在$行向錯字> imagen畫質

<div class="wrapper"><a href="store.php?url=<?php echo $row->url ?>"><img src="images/stores/category/ 

<?php   
if (empty($row->image) || !is_file('images/stores/category/' . $row->image)) { 
    echo 'generic.jpg'; 
}else{     
    echo $row->image; }?>" alt="<?php echo $row->seo ?>"/></a></div>   
    </div> 
    <?php } ?> 
+0

這個解決方案工作!下面的解決方案也起作用! – JeanR

+0

錯字是一個翻譯錯誤,這是真正的字段名稱,數據庫是西班牙語。謝謝 – JeanR

0

介意錯字$ row-> imagen。 正如我所看到的$ row-> image只包含文件名。除非圖片是在當前工作目錄中,你需要file_exists的完整路徑:

file_exists('htdocs/path/to/my/images/' . $row->image)==false) 

要了解你所需要的路徑,放置一個PHP文件到的圖片與內容

die(__FILE__); 
文件夾

最好的問候

+0

感謝您的回答!所有的解決方案的作品,我錯過了路徑,非常感謝 – JeanR

1

file_exists應指向文件系統中的某些內容。

嘗試是這樣的:

if (file_exists('/Library/WebServer/Documents/theimage.jpg')) { 
    echo 'File exists'; 
} else { 
    echo 'Does not exist'; 
} 

OR

if (file_exists('./theimage.jpg')) { 
    echo 'File exists'; 
} else { 
    echo 'Does not exist'; 
} 

,如果我申請到你的代碼是:

<div class="wrapper"><a href="store.php?url=<?php echo $row->url ?>"><img src="images/stores/category/ 
if (empty($row->image) or !file_exists('./images/stores/category/'.$row->image)) { 
    echo 'generic.jpg'; 
}else{     
    echo $row->imagen; }?>" alt="<?php echo $row->seo ?>"/></a></div>   
    </div> 
<?php } ?> 
+0

這工作正常!以前的答案也能正常工作,究竟有什麼區別,我錯過了路徑。 – JeanR