OK… A more familiar approach to iterate an array is to use foreach
. What you would see in normal multiple upload would be an array something like this.
Array
(
[name] => Array
(
[0] => 001.jpg
[1] => 002.jpg
[2] => 003.jpg
[3] => 004.jpg
)
[type] => Array
(
[0] => image/jpeg
[1] => image/jpeg
[2] => image/jpeg
[3] => image/jpeg
)
[tmp_name] => Array
(
[0] => C:\....\....\tmp\php545E.tmp
[1] => C:\....\....\tmp\php545F.tmp
[2] => C:\....\....\tmp\php546F.tmp
[3] => C:\....\....\tmp\php5470.tmp
)
[error] => Array
(
[0] => 0
[1] => 0
[2] => 0
[3] => 0
)
[size] => Array
(
[0] => 55453
[1] => 65521
[2] => 26248
[3] => 57827
)
)
You can see the main array keys name
,type
,tmp_name
, error
and size
but what we are really looking for are the open KEY’s I mentioned, which are shown in each section of the array. So if we just loop through one section, e.g. 'name'
we will be dealing with key =>
value pairs so if we use
foreach($_FILES['userImage']['name'] as $key => $value):
we would see and have access to these $key => $value
pairs.
Array
(
[0] => 001.jpg
[1] => 002.jpg
[2] => 003.jpg
[3] => 004.jpg
)
So now that you have the $key
for each image uploaded, you can use this $key
to get any of the primary Key => Values… You are primarily using 'tmp_name'
but you could also move a copy of the image to a directory and save the image name to the database. But to the point. You will use the key like this.
$_FILES['userImage']['tmp_name'][$key]
Now your previous script uses a header to send the user to a preview page when an image is uploaded. Now that you are changing this to upload multiple images, this header will need to be moved to After the closing foreach bracket or tag so it will only preview the last image uploaded. My version of your image processing looks like this.
if(!empty($_FILES)):
foreach($_FILES['userImage']['name'] as $key => $value):
if(!empty($value)):
if(is_uploaded_file($_FILES['userImage']['tmp_name'][$key])):
$imgData = addslashes(file_get_contents($_FILES['userImage']['tmp_name'][$key]));
$imageProperties = getimageSize($_FILES['userImage']['tmp_name'][$key]);
$sql = "INSERT INTO trial (imageType ,imageData, user_id)
VALUES('{$imageProperties['mime']}', '{$imgData}','".$_SESSION['id']."')";
mysqli_query($db, $sql) or die("<b>Error:</b> Problem on Image Insert<br/>" . mysqli_error($db));
$current_id = mysqli_insert_id($db);
endif;
endif;
endforeach;
//You will preview just the last image
if(!empty($current_id)):
header("Location: preview.php?image_id=".$current_id);
exit;
endif;
endif;