简体   繁体   English

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

[英]uploading multiple files in database server

I want to upload multiple images to mySQL database but I get this error: 我想将多个图像上传到mySQL数据库,但出现此错误:

Warning: Invalid argument supplied for foreach() in. 警告:为foreach()输入了无效的参数。

Here is my code: 这是我的代码:

<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";
            }
}
}
}

?>

Try this: 尝试这个:

  • html - Change the name of the input file to "files[]" to convert it to an array html-将输入文件的名称更改为“ files []”以将其转换为数组
  • php - Loop througth the files with 'for' php-使用“ 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";
            }
        }
    }
}

?>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM