上传数据库服务器中的多个文件

时间:2016-02-23 18:30:24

标签: php

我想将多个图像上传到mySQL数据库,但是我收到了这个错误:

  

警告:为.ach中的foreach()提供的参数无效。

这是我的代码:

<form action="" method="post" enctype="multipart/form-data">
<input type="file" name="files" multiple >
<input type="submit" name="submit">
</form>
<?php

include 'connect.php';

if(isset($_POST['submit'])){
    $name = $_FILES['files']['name'];

    $allowed = array('jpg', 'png', 'jpeg', 'gif', 'bmp');

            foreach($name as $position => $file_name){
            $type = $_FILES['files']['type'];
            $tmp_name = $_FILES['files']['tmp_name'];
            $result = substr(sha1(mt_rand()),0,50);
            $explode = explode(".",$_FILES["files"]["name"]);
            $ext = end($explode);
            $target = "test/".$result.".".$ext;

            if(in_array($ext, $allowed)){           

            if(move_uploaded_file($tmp_name,$target)){
                mysqli_query($con, "INSERT INTO photo VALUES('', '".$target."')");
            echo "all uploaded";
            }
}
}
}

?>

1 个答案:

答案 0 :(得分:0)

试试这个:

  • html - 将输入文件的名称更改为&#34; files []&#34;将其转换为数组
  • php - 使用&#39; for循环传递文件。
<form action="" method="post" enctype="multipart/form-data">
<input type="file" name="files[]" multiple >
<input type="submit" name="submit">
</form>


<?php

include 'connect.php';

if(isset($_POST['submit'])){
    $allowed = array('jpg', 'png', 'jpeg', 'gif', 'bmp');
    $myFile = $_FILES['files'];
    $fileCount = count($myFile["name"]);

    for ($i = 0; $i < $fileCount; $i++) {
        $name = $myFile["name"][$i];
        $type = $myFile['type'][$i];
        $tmp_name = $myFile['tmp_name'][$i];
        $result = substr(sha1(mt_rand()),0,50);
        $explode = explode(".",$myFile["name"][$i]);
        $ext = end($explode);
        $target = "test/".$result.".".$ext;

        if(in_array($ext, $allowed)){

            if(move_uploaded_file($tmp_name,$target)){
                mysqli_query($con, "INSERT INTO photo VALUES('', '".$target."')");
                echo "all uploaded";
            }
        }
    }
}

?>