错误(为foreach()提供的参数无效)使用php上传多个图像时

时间:2017-03-07 08:20:45

标签: php

当我在数据库中上传多个图像时,我得到的错误如下: - 为foreach()提供的参数无效

我的代码: -

<form name="" method="post" enctype="multipart/form-data" action="add_venue_image_do.php">
    <div class="col-lg-12" style=" margin-bottom:16px;">
        <label>Venu Image</label>
        <input multiple required type="file" name="multi_image" class="form-control">
        <input id="venue_hidden_id" value="5" name="venue_hidden_id" type="hidden"> //value 5 indicate business id
        <button type="submit" value="Submit" style="margin-top:15px;" class="btn btn-primary btn-sm pull-right submitMultiImg">Submit </button>
    </div>
</form>

add_venue_image_do.php: -

当PHP代码执行foreach()时,它会抛出错误为foreach()提供的无效参数

<?php
if(isset($_COOKIE['login']))
{
    require("../../root/db_connection.php");
    if(isset($_REQUEST['venue_hidden_id'])){
        $venue_hidden_id=$_REQUEST['venue_hidden_id'];

        foreach($_FILES['image']['tmp_name'] as $key => $tmp_name ): //getting error on this line
            $file_name = $key.$_FILES['multi_image']['name'][$key];
            $file_size =$_FILES['multi_image']['size'][$key];
            $file_tmp =$_FILES['multi_image']['tmp_name'][$key];
            $file_type=$_FILES['multi_image']['type'][$key];    
            $img_ext= pathinfo($file_name,PATHINFO_EXTENSION);

            $q=$db->query("insert into venue_image(v_b_id,v_i_ext,v_img_created_date)
            values($venue_hidden_id,'$img_ext',now())") or die("error");

            $lastID= $db->lastInsertId();
            $imageNewName=$lastID.".".$img_ext;
            move_uploaded_file($file_tmp,"../../venue_image//".$imageNewName);
        endforeach;
        ?>

< script >
    alert('Record Updated Successfully');
    window.location.replace('edit_venue.php?v_id=5');
    < /script>
<?php
    }
    else    {
        ?> < script >
    window.location.replace('add_venue.php');
    < /script>
<?php
    }    
}    
else
{    
    header("location:../index.php");    
}    
?>

2 个答案:

答案 0 :(得分:1)

更改您的HTML代码

<input type="file" name="files[]" multiple/>

你的php代码应该是

foreach($_FILES["files"]["tmp_name"] as $key=>$tmp_name)
            {
// image uploading code 
}

参考link

答案 1 :(得分:0)

您的输入名称仅允许单个参数,如果您想支持多个文件,则需要更改为

<input multiple required type="file[]" name="multi_image" class="form-control">

并使用php循环

<?php
foreach ($_FILES['file'] as $key => $file) {
    $tmpName = $file['tmp_name'];

}