I have a form which uploads files, but this script should also update the current files if they already exists in the database. This is where it stops. Everything works fine in the script, except from the last if/else if that I will include. It is all in a foreach loop, as there is multiple files that can be uploaded. It is after the "move_uploaded_file" it fails.
It uploads all the files, but only uploads one of the rows in database, and also ignore adding more.
I've never tried such an approach before, so I have tried to search a while for an answer, but cannot find what I need. I am probably missing something obvious..
foreach ($_FILES['ufile']['name'] as $f => $name)
switch ($f) {
case '0':
$type = '1';
break;
case '1':
$type = '2';
break;
case '2':
$type = '3';
break;
case '3':
$type = '4';
break;
default:
$type = false;
break;
}
$allowedExts = array(
'pdf',
'doc',
'docx'
);
$extension = end(explode(".", $name));
if ($_FILES['ufile']['error'][$f] == 4) {
continue; // Skip file if any error found
}
if ($_FILES['ufile']['error'][$f] == 0) {
if ($_FILES['ufile']['size'][$f] > $max_file_size) {
$errors[] = "Some errormessage.";
continue; // Skip large files
}
elseif(!in_array($extension, $allowedExts )){
$errors[] = "Some errormessage.";
continue; // Skip invalid file formats
}
elseif($type == false){
$errors[] = "Some errormessage.";
continue; // Skip invalid file formats
}
else{ // No error found! Move uploaded files
if(move_uploaded_file($_FILES["ufile"]["tmp_name"][$f], $path.$name))
$qGetFil = $mysqli->prepare("SELECT * FROM moter_filer WHERE mote_id=?");
$qGetFil->bind_param('s', $_GET['id']);
$qGetFil->execute();
$rGetResults = $qGetFil->get_result();
$rGetFil = $rGetResults->fetch_assoc();
$rGetNewRow = $rGetResults->num_rows;
if($rGetNewRow > '0' && $type == $rGetFil['type']){
unlink($_SERVER['DOCUMENT_ROOT'] . '/filer/' . $rGetFil['fil']);
$stmt = $mysqli->prepare("UPDATE moter_filer SET fil= ? WHERE mote_id= ? AND type= ?");
$stmt->bind_param('sss', $name, $_GET['id'], $type);
$stmt->execute();
$stmt->close();
}elseif($rGetNewRow == '0'){
$stmt = $mysqli->prepare("INSERT INTO moter_filer(type,mote_id, fil) VALUES (?,?,?)");
$stmt->bind_param('sss', $type, $_GET['id'], $name);
$stmt->execute();
$stmt->close();
}
$success[] = "Some sccessmessage.";
}
}
}
I this line:
if(move_uploaded_file($_FILES["ufile"]["tmp_name"][$f], $path.$name))
Ther is no curly braces, so the query is executed only if move_upload_file returns true. Problem is that the rest of the lines are executed even if move_upload_file fails because they are out of the if condition:
$rGetFil = $qGetFil->fetch_array();
$rGetNewRow = $qGetFiler->num_rows;
You are also reading extension from filename instead of using the mime type "type" value inside:
$_FILES['ufile']['type'][$f]