So I have a php foreach loop which inserts however many images you upload in to a directory and creates a row in your DB for it. it works great except it is duplicating the last iteration.
I have tried doing an array_splice
but that didn't work.
I know the query is subject to sql injections and will fix this once I get the iteration duplication sorted.
$errors= array();
foreach($_FILES['userfile']['tmp_name'] as $key => $tmp_name ){
$file_name = time().$_FILES['userfile']['name'][$key];
$file_size =$_FILES['userfile']['size'][$key];
$file_tmp =$_FILES['userfile']['tmp_name'][$key];
$file_type=$_FILES['userfile']['type'][$key];
if($file_size > 2097152){
$errors[]='File size must be less than 2 MB';
}
$query="INSERT INTO table (user_id, filename) VALUES ('$user_id', '$file_name')";
$desired_dir="/items/";
if(empty($errors)==true){
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,"/items/".$file_name);
}else{ //rename the file if another one exist
$new_dir="/items/".$file_name.time();
rename($file_tmp,$new_dir) ;
}
mysql_query($query);
}else{
print_r($errors);
}
}
if(empty($error)){
echo "Success";
}
if ($conn->query($query) === TRUE) {
echo "done";
} else {
echo "Error: " . $query . "<br>" . $conn->error;
}
any ideas as to why its doing this?
thanks in advance!