I am trying to upload multiple images to server and mysql database, however the first image out of the multiple images is not being uploaded.
I iterate through the selected files and trying to upload each image in a for loop. All the images upload correctly except the first image.
Here is my html to select multiple files:
<form action="imageUpload.php" method="post" enctype="multipart/form-data">
Select Image File to Upload:
<input type="file" name="files[]" multiple>
<input type="submit" name="submit" value="Upload">
My php codes is as follows:
<?php
include("php/db.php");
$statusMsg = '';
// Count # of uploaded files in array
$total = count($_FILES["files"]["name"]);
// File upload path
$targetDir = "productImages/";
if(isset($_POST["submit"]) && !empty($_FILES["files"]["name"]))
{
for( $i=0 ; $i < $total ; $i++ )
{
// Allow certain file formats
$allowTypes = array('JPG','jpg','png','jpeg','gif');
$fileName = basename($_FILES["files"]["name"][$i]);
$targetFilePath = $targetDir . $fileName;
$fileType = strtolower(pathinfo($targetFilePath,PATHINFO_EXTENSION));
if(in_array($fileType, $allowTypes))
{
// upload file to temporary location
if (is_uploaded_file($_FILES["files"]["tmp_name"][$i]))
{
// Upload file to server
if(move_uploaded_file($_FILES["files"]["tmp_name"][$i], $targetFilePath))
{
// Insert image file name into database
$insertSQL = "INSERT into images (file_name, uploaded_on) VALUES ('".$fileName."', NOW())";
if(openConnection())
{
$insert = insertQuery($insertSQL);
}
closeConnection();
if($insert){
$statusMsg = "The file ".$fileName. " has been uploaded successfully.";
}else{
$statusMsg = "File upload failed, please try again.";
}
}
else
{
$statusMsg = "Sorry, there was an error uploading your file.";
}
}
else
{
$statusMsg = "Sorry, file could not upload to temp location.";
}
}
else
{
$statusMsg = 'Sorry, only JPG, JPEG, PNG, GIF files are allowed to upload.';
}
}
}else{
$statusMsg = 'Please select a file to upload.';
}
echo "<br>" . $statusMsg;
?>
Can anyone please identify what is the issue?