Louie
Louie

Reputation: 319

how to upload multiple image file in one transaction using php and mysqli?

I'm trying to insert multiple images in database per transaction, but each image has its own input types. But when I submit the form, I get the error that my $file_upload = $_FILES['file_upload'.$i]; from my post.php is an "undefined index" . Are the file-upload1, file-upload2, file-upload3 from my HTML are not the correct way to do this? Please help. Thank you.

My php code is:

include 'dbcontroller.php';
if(isset($_POST['submit'])) {
    for ($i = 1; $i <= 3; $i++) {
        $file_upload = $_FILES['file_upload'.$i];

        $file=(rand(1000,100000)."-".$file_upload['name'.$i]);
        $type=$file_upload['type'.$i];
        $size=$file_upload['size'.$i];
        $loc=$file_upload['tmp_name'.$i];

        $new_size=$size/1024; // file size in KB

        // make file name in lower case
        $new_file_name = strtolower($file);
        // make file name in lower case

        $final_file=str_replace(' ','-',$new_file_name);

        if(move_uploaded_file($loc, '..admin/officers-avatars/'.$final_file)) {
            $result = mysqli_query($conn,"INSERT INTO images VALUES ('$final_file', '$new_size', '$type')")
            or die(mysqli_error($conn));
        }
    }
}

Below is my HTML

<form action="post.php" method="post" enctype="multiple/form-data">
	<input type="file" name="file-upload1" /><br><br>
	<input type="file" name="file-upload2" /><br><br>
	<input type="file" name="file-upload3" /><br><br>

	<input type="submit" name="submit" value="SAVE"/>
</form>

Upvotes: 2

Views: 924

Answers (1)

Felippe Duarte
Felippe Duarte

Reputation: 15131

You have a typo: Change enctype="multiple/form-data" for enctype="multipart/form-data".

Anyway, I would suggest you to use an array in name attribute instead:

<form action="post.php" method="post" enctype="multipart/form-data">
    <input type="file" name="fileupload[]" /><br><br>
    <input type="file" name="fileupload[]" /><br><br>
    <input type="file" name="fileupload[]" /><br><br>

    <input type="submit" name="submit" value="SAVE"/>
</form>

Then in PHP you use this:

foreach($_FILES['fileupload'] as $file) {
    ....
}

Or you can use multiple:

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

Upvotes: 2

Related Questions