2011-12-09 78 views
2

顯示在PHP圖像我試圖使用PHP用下面的代碼試圖從MySQL數據庫

<?php 
header('Content-type: image/png'); 
$port = "*"; 
$server = "*:".$port; 
$dbname ="*"; 
$user = "*"; 

$conn = mysql_connect ("$server", "$user", "$pass") or die ("Connection 
Error or Bad Port"); 

mysql_select_db($dbname) or die("Missing Database"); 


    $speakerPic = $_POST['speakerPic']; 
    $query = "SELECT Speaker.speaker_picture AS image FROM Speaker JOIN Contact c USING(contact_id) 
    WHERE c.lname = '"; 
    $query .= $speakerPic."';"; 


$result = mysql_query($query,$dbname); 
$result_data = mysql_fetch_array($result, MYSQL_ASSOC); 

echo $result_data['image']; 
?> 

我保持在接收此錯誤,所述的圖像「,以顯示圖像.../query2.php 「不能顯示,因爲它包含錯誤。

對不起,繼續擾亂你們,但誰能告訴問題是什麼?

+1

小心任何輸出任何來自引入的腳本。請務必消除標籤之外的任何內容。實際上,您應該完全刪除您的關閉?>標記以確保它後面沒有空格。確保你的腳本沒有迴應某種錯誤信息。 –

+0

這些錯誤到底是什麼? – mugetsu

+0

使用瀏覽器的開發人員工具查看圖像的HTTP請求。特別要注意'Content-Length'標題。看看這是不是圖像的大小(我認爲你已經知道)的幾個不同的圖像不同。如果不同,有什麼區別?不同的圖像的差異是相同還是保持不變? – Jon

回答

0

不會說謊,OP代碼有很多不好的地方。

  1. 你應該從數據庫ID來拉動的圖像,而不是一些字符串
  2. 你沒有消毒的VAR在查詢中使用
  3. 你是不是服務的默認圖像,如果不存在
  4. 另外,我會建議存儲文件uris在你的數據庫中,而不是實際的圖像(blob)。你應該在你的文件系統上存儲一個指向圖像的指針。

不打算清理代碼太多,只是讓它不那麼糟糕。我會建議沿着這些線(未經測試)的東西:

// Utility.php 
class Utility 
{ 
    /** 
    * 
    * @param mixed $id is abstract, could be name or an actual id 
    * @return string? 
    */ 
    public static function getImage($id) 
    { 
     try { 
      $port = "*"; 
      $server = "*:".$port; 
      $dbname ="*"; 
      $user = "*"; 

      $conn = mysql_connect ("$server", "$user", "$pass"); 

      if (!$conn) { 
       throw new Exception("Connection Error or Bad Port"); 
      } 

      if (!mysql_select_db($dbname)) { 
       throw new Exception("Missing Database"); 
      } 

      $query = "SELECT Speaker.speaker_picture AS image FROM Speaker JOIN Contact c USING(contact_id) WHERE c.lname = " . mysql_real_escape_string($id). ";"; 

      $result = mysql_query($query,$dbname); 
      $result_data = mysql_fetch_array($result, MYSQL_ASSOC); 

      if (!isset($result_data['image'])) { 
       throw new Exception('Image not found'); 
      } 

      echo $result_data['image']; 

     } catch Exception($e) { 

      error_log($e->getMessage(); 

      return file_get_contents('/path/to/some/default/image.png'); 
     } 
    } 
} 

// image.php 
require_once 'Utility.php'; 

header('Content-type: image/png'); 
ob_start(); 
Utility::getImage($_POST['speakerPic']); 
$image = ob_get_flush(); 

echo $image; 
+0

謝謝。我絕對是一個初學者,我會試着圍繞你的代碼繞過我的頭腦。我真的很感激你花時間,這個社區是真棒。 – user1087799

+0

@ user1087799:不用擔心......並不意味着過分苛刻。 –