2014-04-12 52 views
0

嗨,我試圖從數據庫中接收我的圖像。我已經可以插入圖像,但我不知道它是否出現錯誤,或者我在獲取圖像時做了錯誤處理。沒有收到數據庫中的圖像PHP LongBlob

用於插入圖像的代碼:

public function Save(){ 
     /*** check if a file was uploaded ***/ 
     if(is_uploaded_file($_FILES['userfile']['tmp_name']) && getimagesize($_FILES['userfile']['tmp_name']) != false) 
      { 
      /*** get the image info. ***/ 
      $size = getimagesize($_FILES['userfile']['tmp_name']); 
      /*** assign our variables ***/ 
      $type = $size['mime']; 
      $imgfp = fopen($_FILES['userfile']['tmp_name'], 'rb'); 
      $size = $size[3]; 
      $name = $_FILES['userfile']['name']; 
      $maxsize = 99999999; 


      /*** check the file is less than the maximum file size ***/ 
      if($_FILES['userfile']['size'] < $maxsize) 
       { 
       /*** connect to db ***/ 
       $db = new Db(); 

       /*** our sql query ***/ 
       $sql = "INSERT INTO Foto (image_type ,image, image_size, image_name) 
        VALUES ('". $type ."', 
          '". $imgfp ."', 
          '". $size ."', 
          '". $name ."');"; 
       $db->conn->query($sql); 

       $sql = "SELECT * FROM Foto ORDER BY id DESC LIMIT 1;"; 
       $select = $db->conn->query($sql); 

       $numberofRows = $select->num_rows; 

       if($numberofRows == 1) 
       { 
        while ($oneSelect = $select->fetch_assoc()) 
        { 
         return $oneSelect; 
        } 
       } else { 
        throw new Exception("Fout"); 
       } 


       } 
      else 
       { 
       throw new Exception("Bestand is te groot"); 
       } 
      } 
     else 
      { 
      throw new Exception("Dit extensie is niet ondersteund"); 
      } 
     } 

用於加載圖像的代碼:

<?php 
include_once("classes/Db.class.php"); 
//$id = $_GET['id']; 
$id = "33"; 
$db = new Db(); 
$sql = "SELECT image, image_type FROM Foto WHERE id = '". $id ."';"; 
$result = $db->conn->query($sql); 
$row = $result->fetch_assoc(); 
if(sizeof($row) == 2) 
{ 
    header("Content-type: ".$row['image_type']); 
    echo $row['image']; 
} 
else 
{ 
    throw new Exception("Out of bounds Error"); 
} 

>

回答

0

你不是實際插入的圖像數據?請閱讀fopen()函數,它不返回圖像數據,而是返回一個文件句柄,然後可用於讀取或寫入文件(例如,使用fread()fwrite())。簡單的出路是使用file_get_contents()

但請接受我的建議,將圖像存儲在數據庫中是一種非常糟糕的做法。它們是文件,最好存儲在文件系統中(因此名稱)。由於不需要執行PHP請求,因此也可以更快地爲它們提供服務。相反,將文件名和文件的相對路徑保存在數據庫中。