2

I have used the form below to upload multiple images to my server.

<form name="addimageForm" id="addimageForm" method="post" action="" enctype="multipart/form-data">              
    Gallery Image: 
    <input name="image_name[]" type="file" id="image_name" multiple="true">
    <input type="submit" name="addCatImage"/>
</form>

But I am confused how I should loop through it so that I can insert multiple images in my database. I used the code below, and when I run it, even when I select a image, 4 rows are inserted in my table. I think it is inserting all of the array fields(name, size, tmp_name). How can i solve the problem?

foreach ($_FILES[image_name] as $file) {
    $access->uploadSubCatImages();
}

3 Answers 3

1

PHP makes the attributes themselves arrays. Yeah, I don't know who decided that.

// PHP does this:
$_FILES['image_name']['name'] = array('file1', 'file2', 'file'3);
$_FILES['image_name']['type'] = array('...', ...);

http://www.php.net/manual/en/features.file-upload.multiple.php

Sign up to request clarification or add additional context in comments.

Comments

0

$_FILES is multidimensional. With the syntax that you used, the Filenames would be accessible in

$_FILES['image_name']['name'][0] # for the first one
$_FILES['image_name']['name'][1] # for the second one

and so on. Here is a link for reference Uploading Multiple Files

Comments

0

First, the index to the $_FILES array is a string. Although will PHP 'eat' it and just throw a E_NOTICE, you should not do it. Use 'image_name' instead. (note the quotes)

Also the array structure may be different from what you've exptected. The following will loop trough the filen ames for example:

foreach ($_FILES['image_name']['name'] as $filename) {
    // do work here
}

Please refer to the documentation on $_FILES and especially this doc page.

3 Comments

FYI, unquoted identifiers are interpreted as strings by PHP, with an E_NOTICE.
@Rygu To be more specific, they're considered undefined constants, and PHP handles the error by interpreting the constant name as its value. This may change in a future version, so you should not rely on this.
@AgentConundrum Thanks for the precise explanation. Indeed, one should not rely on it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.