2011-06-03 67 views
2

我最近開始學習Javascript,但仍然沒有在這個問題上的專家。
所以我想知道是否有人云幫助我。如何在php無法從服務器提取圖像時顯示圖像?

我使用MySQL數據庫和PHP

我的數據庫表構建投資組合的網站有3個冒號:name, small_image, description

我已經設置了我的PHP,以便它提取namesmall_image

$name  = htmlentities($row['name']); 
$image_small = "images/" . $row['image_small']; 

,並將它顯示是這樣的:

$name 
< img src='$image_small' with='$width' height='$height' /> 

我唯一的問題是,當我進入管理頁面,添加了新的工作,在網站上沒有圖像出現一個空的空間。

我想要做的是有一個圖像,可以取代失蹤的圖像?

有沒有辦法讓它工作?或者更好,簡單的方法來做到這一點?

我真的很感激它。

這裏不工作是完整的代碼。

< - - - - - - - - - - - - - - - - - - - - 全碼 - - - - - - - - - - - - - - - - >

// Loop through all of the records returned from the query 
    while($row = mysql_fetch_array($results)) { 
     // collect data from each field 
     $id   = $row['id']; 
     $name  = htmlentities($row['name']); 
     $desc_short  = htmlentities($row['desc_short']);   

     if(isset($row['image_small'])){ 
      $image_small = "images/jewelry/small/" . $row['image_small']; 
     } 

     else{ 
      $image_small = "images/blank.jpg"; 
     } 


echo " 

     <li class='column_$x $last_row_class'> 
     <a href='details.php?id=$id'> 
      <img src='$image_small' with='$width' height='$height' /> 
     </a> 
     <p class='product_name'><a href='details.php?id=$id'>$name</a></p> 
     <p class='product_desc'>$desc_short</p> 
     $rating_div 
     </li>"; 
+0

你把blank.jpg圖像放在圖像文件夾? – 2011-06-03 05:28:43

回答

0

試着改變你的第一個代碼塊上面的代碼是這樣的:

$name   = htmlentities($row['name']); 
$image_small = ($row['image_small'] != '') ? "images/" . $row['image_small'] : '/path/to/default.png'; 

它所做的是檢查是否$row['image_small']有一個值,如果是用它來$image_small,否則設置$image_small爲默認的路徑小圖像。

1

如果數據庫中不存在圖像,則應顯示空白圖像(默認圖像)。 例如

$name = htmlentities($row['name']); 
if(isSet($row['image_small'])){ 
     $image_small = "images/" . $row['image_small']; 
} 
else{ 
    $image_small = "images/blank.jpg"; 
} 

注意:您應該將blank.jpg放在圖像文件夾中。

我建議你在圖像上傳到系統文件夾時將圖像名稱保存在數據庫中。 或者你可以在文件夾中查看您的圖像文件,如下所示:

<?php 
$filename = "images/" . $row['image_small']; 

if (!file_exists($filename)) { 
    $image_small = "images/blank.jpg"; 
} 
?> 

享受!!!!!!!

+0

感謝您的幫助,但仍未顯示。 – contesta 2011-06-03 05:19:18

+0

你應該把blank.jpg放在圖像文件夾中,然後它就可以工作。 – 2011-06-03 05:30:37

0

除了其他建議,您可以使用MySQL中的ISNULL()函數返回默認圖像名稱。例如,創建你的圖像目錄爲Default.png圖像,並在查詢中使用這樣的:

SELECT 
    name, 
    IF(ISNULL(small_image),'default.png',small_image) AS "small_image", 
    description 
FROM 
    images; 

不是說這一定是一個更好的答案,只是一個替代品。

0

客戶端解決方案是使用img標籤的「onerror」屬性。 這就像︰

<img src='$image_small' with='$width' height='$height' onerror='this.src = "/images/default.jpg" ;' />