多个文件上载不会在数据库中插入所有文件

时间:2017-11-11 20:11:57

标签: php mysql database image upload

我在数据库中插入有问题。它只插入第一个上传的图像:/这是我的PHP代码:

    function reArrayFiles(&$file_post) {

    $file_ary = array();
    $file_count = count($file_post['name']);
    $file_keys = array_keys($file_post);

    for ($i=0; $i<$file_count; $i++) {
        foreach ($file_keys as $key) {
            $file_ary[$i][$key] = $file_post[$key][$i];
        }
    }

    return $file_ary;
    }

    $file_ary = reArrayFiles($_FILES['files']);
    $allowedTypes = array(IMAGETYPE_PNG, IMAGETYPE_JPEG, IMAGETYPE_GIF);        

    foreach($file_ary as $key => $file){
        static $i = 1;

        if($file['error'] == 4){
            continue;
        }elseif(!in_array(exif_imagetype($file['tmp_name']), $allowedTypes)){
            $error = '<span style="color:red">Filename '.$file['name'].' <b>type</b> is not allowed.</span><br>';
        }elseif($file['size'] > 2097152){
            $error = '<span style="color:red">Filename '.$file['name'].' exceeds maximum allowed <b>size</b></span>.<br>';
        }else{              
            $getfilename= $file["name"];
            $FileName="U[$user->id].$getfilename";
            $time = time();
            $output_dir = "uploads/";               

            if(!file_exists("uploads/".$FileName)){                 
                move_uploaded_file($file["tmp_name"], "uploads/".$FileName);
            }else{
                $FileName="$time.$getfilename";
                move_uploaded_file($file["tmp_name"], "uploads/".$FileName);
            }

            mysql_query("INSERT INTO ads_pictures (path, filename, timestamp) VALUES('".$output_dir."', '".$FileName."', '".$time."')");            
        }
        $i++;
    }

这是HTML代码:

                        <form method="post" enctype="multipart/form-data" action="">
                            <input id="image" type="file" name="files[]" accept="image/*">
                            <input id="image" type="file" name="files[]" accept="image/*">
                            <input id="image" type="file" name="files[]" accept="image/*">
                            <input id="image" type="file" name="files[]" accept="image/*">
                            <input name="submit" class="btn submit" value="Upload" type="submit">
                        </form>

它通常应该将所有上传的文件插入数据库,但不幸的是它只插入第一个选定的文件。谢谢你的帮助。

1 个答案:

答案 0 :(得分:0)

您是否考虑过更换:

  foreach($file_ary as $key => $file){
    static $i = 1;

用这个:

$i = 1;
foreach($file_ary as $key => $file){

如果有帮助,请告诉我们。