【问题标题】:Get multiple images through Json通过Json获取多张图片
【发布时间】:2017-06-14 10:24:45
【问题描述】:

我正在尝试遍历所有可用图像并将它们提交到客户端。使用下面的代码,我只能在一次上传多张图片时获得一张。完全相同的代码也在我的 php 页面中,并完美地显示了所有图像。所以我认为这与我尝试构建数组或循环本身有关。 ;}

我知道我的脚本目前容易受到 sql 注入的影响,稍后会进行保护。;)

$sqlhhh = "SELECT * FROM userphotos WHERE photo_name='".$row['photo_title']."' 
AND photo_ownerid='".$row['streamitem_creator']."' 
AND photo_datetime='".$row['streamitem_timestamp']."' ORDER BY photo_id DESC";
$resulthhh = mysqli_query ($mysqli,$sqlhhh)or die(mysqli_error($mysqli)); 
$photo_num=mysqli_num_rows($resulthhh);

while ($rowhhh = mysqli_fetch_assoc($resulthhh)) {
    $json = array(
        'posts' => array(),
    );

    $images = array();
    $image[] = $rowhhh['photo_imagedata'];
}

foreach ($image as  $ima) {
    if($photo_num==1){
        $posts['streamitem_imageuploaded']='<img  src="data:image/jpeg;base64,'. base64_encode($ima) .'" />';
    }else{
        $posts['streamitem_imageuploaded']='<img class="stream_images" style="width:235px;height:200px;object-fit:cover;margin:2px;padding:2px;" src="data:image/jpeg;base64,'. base64_encode($ima) .'" />';
    }
}
$json['posts'][] =  $posts;

【问题讨论】:

    标签: php arrays json loops foreach


    【解决方案1】:

    这是因为您在 while() 循环的每次迭代中都初始化了 $images 数组。将此语句 $images = array(); 置于 while() 循环之外。同样的逻辑也适用于$json 数组。

    另外,看看下面两行,

    $image[] = $rowhhh['photo_imagedata'];
    

    和

    foreach ($image as  $ima) { ...
    

    $image 是未定义,你必须在这些地方使用$images 数组。

    因此,请按照以下方式重构您的 while() 和 foreach() 循环,

    // your code
    $photo_num=mysqli_num_rows($resulthhh);
    $json = $images = array();
    while ($rowhhh = mysqli_fetch_assoc($resulthhh)) {
        $images[] = $rowhhh['photo_imagedata'];
    }
    
    foreach ($images as  $ima){
        $posts = array();
        if($photo_num==1){
            $posts['streamitem_imageuploaded']='<img  src="data:image/jpeg;base64,'. base64_encode($ima) .'" />';
        }else{
            $posts['streamitem_imageuploaded']='<img class="stream_images" style="width:235px;height:200px;object-fit:cover;margin:2px;padding:2px;" src="data:image/jpeg;base64,'. base64_encode($ima) .'" />';
        }
        $json['posts'][] =  $posts;
    }
    

    【讨论】:

    • 谢谢你。现在工作。很高兴知道我离得不远。
    猜你喜欢
    • 1970-01-01
    • 2016-02-04
    • 1970-01-01
    • 1970-01-01
    • 2012-03-23
    • 2011-02-21
    • 2015-06-18
    • 1970-01-01
    • 2023-03-13
    相关资源
    最近更新 更多