【问题标题】:array not displaying contents while using a BLOB in database在数据库中使用 BLOB 时数组不显示内容
【发布时间】:2018-03-18 11:35:39
【问题描述】:

我正在使用 json 和 php 来显示我的数据库的内容,这一直有效,直到我在数据库中实现了一个 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

【问题讨论】:

  • 当您转储 $rows 时,您希望看到什么?该“blob”是图像的二进制数据,正是您所描述的。如果你想通过json_encode传输它,你可能需要先base64_encode这个blob,然后在收到它之后base64_decode它......
  • 我看不出您实际上是在哪里尝试在代码中使用 blob 数据。我什至在您的帖子中也没有看到任何问题。
  • @cale_b 问题是当我尝试显示页面为空白的数据时
  • @PatrickQ 问题是当我尝试显示页面为空白的数据时
  • 疑难解答:逐一检查代码的每个部分。你知道var_dump( $rows) 做了什么——现在试试var_dump( $picturetxt );,然后是var_dump($cl);,等等,直到你看到哪里出了问题/没有工作。

标签: php json blob


【解决方案1】:

在这里,我有点担心,因为我怀疑问题在于您的 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
}

【讨论】:

  • 如果您使用此答案,请在此处发表评论,并参考答案中的代码。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-08-02
  • 2011-04-10
  • 2014-02-21
  • 1970-01-01
  • 2012-04-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多