For den første fejl er fejlarrayet uden for foreahen, så du sletter ikke fejlen for hver fil, og forespørgslen, der skal indsættes, er uden for, hvis det kontrollerer fejl, så den bliver altid eksekveret
For den anden fejl er det samme, forespørgslen udføres altid, du skal kontrollere, om filen er uploadet.
<?php
include_once('connect.php');
if(isset($_FILES['files'])){
$filesErrors = 0;
foreach($_FILES['files']['tmp_name'] as $key => $tmp_name ){
// MOved errors inside the foreach to clear it each loop
$errors = array();
// Check file is uploaded
if ($_FILES['files']['error'][$key] == UPLOAD_ERR_NO_FILE){
// Continue with the next file
continue;
}
$file_name = $key.$_FILES['files']['name'][$key];
$file_size = $_FILES['files']['size'][$key];
$file_type = $_FILES['files']['type'][$key];
if($file_type == "image/gif"){
$sExt = ".gif";
} elseif($file_type == "image/jpeg" || $file_type == "image/pjpeg"){
$sExt = ".jpg";
} elseif($file_type == "image/png" || $file_type == "image/x-png"){
$sExt = ".png";
}
if (!in_array($sExt, array('.gif','.jpg','.png'))) {
$errors[] = "Image types alowed are (.gif, .jpg, .png) only!";
}
$file_tmp = $_FILES['files']['tmp_name'][$key];
$file_type = $_FILES['files']['type'][$key];
if($file_size > 2097152){
$errors[]='File size must be less than 2 MB';
}
if(empty($errors) == true){
$desired_dir = "user_data";
// Execute query inside the errors check
$query = "INSERT into offers_pics (`offer_id`,`pic_name`,`pic_type`) VALUES ('$user_id','$file_name','$file_type'); ";
$result = mysqli_query($link,$query);
if(is_dir($desired_dir) == false){
mkdir("$desired_dir", 0700); // Create directory if it does not exist
}
if(is_dir("$desired_dir/".$file_name) == false){
move_uploaded_file($file_tmp,"$desired_dir/".$file_name);
}else{ // rename the file if another one exist
$new_dir = "$desired_dir/".$file_name.time();
rename($file_tmp,$new_dir) ;
}
}else{
$filesErrors++;
print_r($errors);
}
}
if ($filesErrors == 0){
echo 'Success';
}
}
?>
<form action="" method="POST" enctype="multipart/form-data">
<input type="file" name="files[]"> <br/>
<input type="file" name="files[]"> <br/>
<input type="file" name="files[]"> <br/>
<input type="file" name="files[]"> <br/>
<input type="file" name="files[]" > <br/><br/>
<input type="submit"/>
</form>