2017-03-05 43 views
0

我是我的數據庫中的圖像數據作爲mediumblob並試圖檢索它作爲圖像時,用戶通過它的相應的ID選擇圖片。在任何人跳過我的喉嚨之前,是的,我意識到這是一個更順暢的過程,存儲在文件服務器上,並以這種方式檢索,但這是一個班級,這是教授想要的。獲取「圖像無法顯示,因爲它包含錯誤」

<HTML> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
<title>BLOB Data Type Tutorial</title> 
</head> 

<body> 
<form action="images.php" method="POST" enctype="multipart/form-data"> 
    Select Picture: <input type="pictureID" name="pictureID"> <input type="submit" value="submit" name="submit"> 

</form> 
<?php 

    $link = mysqli_connect('127.0.0.1:3306','user',''); 
    $link; 
    mysqli_select_db($link, "media"); 

    $sql = "SELECT * FROM images"; 
    $result = mysqli_query($link,$sql); 
    echo "<table>"; 
    echo "<tr><th>Picture</th><th>Size KB</th><th>Title</th></tr>"; 

    if($result === FALSE){ 
     echo "failed"; 
     die(mysql_error()); 
    } 

    while($row = mysqli_fetch_array($result)) { 
     $Picture = $row['Picture']; 
     $Size = $row['Size KB']; 
     $Title = $row['Title']; 
     echo "<tr><td style ='width: 50px;'>".$Picture."</td><td style='width: 60px;'>".$Size."</td><td>".$Title."</td></tr>"; 
    } 

    echo "</table>"; 

    if(isset($_POST['pictureID'])) 
    { 
    $imgId = $_POST['pictureID']; 
    echo $imgId; 
    if (!empty($imgId)) { 
    $sqliCommand = "SELECT Picture FROM images WHERE Picture = $imgId"; 
    $result = mysqli_query($link, $sqliCommand); 
    $row = mysqli_fetch_assoc($result); 
    header("Content-type: image/jpeg"); 
    echo $row['Image']; 
    } 
    } 
    else 
    { 
     echo "^ Please select a picture! ^"; 
    } 
?> 


<br> 
<h4> 
    <a href="./index.html">Main Menu</a> <br> 
</h4> 
</body> 
</HTML> 

任何提示/幫助表示讚賞!

+0

找一位新教授。他真的不知道他在教什麼,如果那是他想要你學習的東西。有許多事情是錯誤的,不僅僅是圖像數據在數據庫中的存儲,還有缺乏準備好的語句(用戶輸入),表格中的輸出(儘管如果存在大量具有相應數據的圖像,這可能是有保證的這應該是可比的/可排序的)。 – junkfoodjunkie

回答

0

這是因爲頁面頂部也有html代碼導致的。當執行header("Content-type: image/jpeg");時,chrome會將整個頁面的內容解釋爲包含html的圖像數據。

要解決這個問題,當id在腳本頂部傳遞代碼時輸出圖像輸出,並在輸出圖像時立即退出腳本,否則它下面的代碼也會輸出。

它應該做的事是這樣的:

<?php 
    //this should be at top of php file, above html code 
    link = mysqli_connect('127.0.0.1:3306','user','');  
    mysqli_select_db($link, "media"); 
    if(isset($_POST['pictureID'])) 
    { 
     $imgId = $_POST['pictureID']; 
     //echo $imgId; nothing else expect image should be echoed 
     if (!empty($imgId)) { 
      $sqliCommand = "SELECT Image FROM images WHERE Picture = $imgId";// select Image here so not select picture as you did earlier 
      $result = mysqli_query($link, $sqliCommand); 
      $row = mysqli_fetch_assoc($result); 
      mysqli_close($link);//close mysqli as script gonna exit after echoing image. 
      header("Content-type: image/jpeg"); 
      echo $row['Image']; 
      exit();// this is important 
     } 
    } 
?> 
<html> 
    <body> 
    <!-- rest of the code --> 

閱讀我在寫代碼的註釋。

如果您將標頭設置爲圖像類型,則頁面上一定不會出現圖像二進制代碼。

如果問題仍然存在,那麼註釋標題行(這將使頁面以文本形式顯示),並查看頁面中是否有其他內容以二進制形式呈現圖像數據。

+0

謝謝你,先生,可能Hera對待你好! – blackmail242

相關問題