2017-10-06 50 views
-1

我使用json和php來顯示數據庫的內容,直到我爲數據庫實現了一個blob值才能存儲我的圖片,現在當我運行時頁面它不顯示數據,我使用的代碼是波紋管數組在數據庫中使用BLOB時不顯示內容

library2頁

<?php 
ini_set("display_errors",1); 
    error_reporting(E_ALL); 

function getAllPictures() { 
    // include the login credentials 
    include ("loginasdf.php") ; 
    // connect to the database to get current state 
    $conn = mysqli_connect($servername, $username, $password, $dbname); 


    if (!$conn) { die("Connection failed: " . mysqli_connect_error()); 
    echo "fail";  } 
    $sql = "SELECT * FROM Pictures" ; 
    $result = mysqli_query($conn, $sql); 
    // convert to JSON 

    $rows = array(); 
    while($r = mysqli_fetch_assoc($result)) { 
     $rows[] = $r; 
    } 
    var_dump($rows); 
    return json_encode($rows); 
    } 

顯示頁

<?php 
include("library2.php") ; 
$picturetxt = getAllPictures() ; 
$picturejson = json_decode($picturetxt) ;  

    $cl = $picturejson; 
    for ($i=0 ; $i<sizeof($cl) ; $i++) { 
    echo "<a href=displaycontact2.php?id=" ; 
    echo $cl[$i] -> id ; 
    echo ">" ; 
    echo $cl[$i] -> hname ; 
    echo "</a><br/>" ; 
    echo "</a><br/>" ; 
     echo "ID: "; 
      echo $cl[$i] -> ID; 
     echo "<br/>"; 
     echo "Name: "; 
      echo $cl[$i] -> hname; 
     echo "<br/>"; 
     echo "Image: "; 

     ?> 
<html>  
    <img src=himage alt="himage" style="width:304px;height:228px;"> 
</html> 
<?php 
    } 
    ?> 

I get this when i dump $rows

+1

,你會期望看到什麼,當你傾倒$行?這個「blob」是圖像的二進制數據,正如你所描述的那樣。如果你想通過'json_encode'傳輸它,你可能需要'先base64_encode' blob,然後'base64_decode'它被接收後...... –

+0

我沒有看到你實際嘗試使用blob數據的位置在你的代碼中。我甚至不會在你的帖子中看到問題。 –

+0

@cale_b問題是當我試圖顯示數據的頁面是空的 – mattdoesnthaveaclue

回答

0

因爲我懷疑問題在於你的json_encode/json_decode沒有很好地處理二進制圖像數據。

爲了解決這個問題,你應該在分配給你的數組之前使用base64_encode,然後在json_decode之後使用base64_decode

事情是這樣:

$rows = array(); 
while($r = mysqli_fetch_assoc($result)) { 
    // base64_encode the image only 
    $r['himage'] = base64_encode('himage'); 
    $rows[] = $r; 
} 

然後:

$picturejson = json_decode($picturetxt);  

// may I suggest some simpler code below... don't use for ($i=0... 
// $cl = $picturejson; 
// for ($i=0 ; $i<sizeof($cl) ; $i++) { 

// instead, use foreach($picturejson.... 
foreach ($picturejson AS $row) { 
    // base64_decode the image data 
    $row->himage = base64_decode($row->himage); 
    echo "<a href=displaycontact2.php?id=" ; 
    // access $row instead of $cl[$i].... 
    echo $row->id ; 
    // ... etc 
    echo "<img src='{$row->himage}'>"; 
    // ... etc 
} 
+0

如果你使用這個答案,你可以在這裏評論,並參考答案中的代碼。 –