简体   繁体   中英

uploading multiple files in database server

I want to upload multiple images to mySQL database but I get this error:

Warning: Invalid argument supplied for foreach() in.

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
  • php - Loop througth the files with '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";
            }
        }
    }
}

?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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