Reputation: 1965
I am creating a form.
There are several field types in the form.
Among which i have a file upload box which can be populated.
User can attach several documents on the file upload input.
On submitting the file names should be saved in db in same column separated by commas.
For single file i know how to do it, but since it is cloned i am confused.
<span class="button btn-primary"> Choose File </span>
<input type="file" class="gui-file required" name="docs[]" onChange="document.getElementById('orderupload1').value = this.value;">
<input type="text" class="gui-input" name="orderupload1" id="orderupload1" placeholder="Attach Domcuments Here..." readonly>
Form and field population works good with the above code and some JS.
Now the issue is how to insert every populated field file name separated by comma in same column.
I did already for single field as follows:
$docs=$_FILES['docs[]']['name'];
$temp_doc_name=$_FILES['docs[$i]']['tmp_name'];
if($docs!=''){
if ($temp_doc_name != ""){
$newFilePath1 = "uploadFiles/" . $docs;
if(move_uploaded_file($temp_doc_name, $newFilePath1)) {
}
}
}
$sql = "insert into students (documents) values(LAST_INSERT_ID(), '$docs')";
Upvotes: 2
Views: 419
Reputation: 1633
replace you code with foreach as below.
foreach ($_FILES['docs']['name'] as $key => $val) {
if (move_uploaded_file($_FILES['docs']['tmp_name'][$key], $newFilePath1)) {
/* FILE IS UPLOADED SUCCESSFULLY */
}
}
Upvotes: 1
Reputation: 4166
Check below demo and replace your code accordingly.
HTML
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Multiple File Ppload with PHP</title>
</head>
<body>
<form action="" method="post" enctype="multipart/form-data">
<input type="file" id="file" name="files[]" multiple="multiple" accept="image/*" />
<input type="submit" value="Upload!" />
</form>
</body>
</html>
PHP Code
$valid_formats = array("jpg", "png", "gif", "zip", "bmp");
$max_file_size = 1024*100; //100 kb
$path = "uploads/"; // Upload directory
$count = 0;
if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST"){
// Loop $_FILES to exeicute all files
foreach ($_FILES['files']['name'] as $f => $name) {
if ($_FILES['files']['error'][$f] == 4) {
continue; // Skip file if any error found
}
if ($_FILES['files']['error'][$f] == 0) {
if ($_FILES['files']['size'][$f] > $max_file_size) {
$message[] = "$name is too large!.";
continue; // Skip large files
}
elseif( ! in_array(pathinfo($name, PATHINFO_EXTENSION), $valid_formats) ){
$message[] = "$name is not a valid format";
continue; // Skip invalid file formats
}
else{ // No error found! Move uploaded files
if(move_uploaded_file($_FILES["files"]["tmp_name"][$f], $path.$name))
$count++; // Number of successfully uploaded file
}
}
}
}
Upvotes: 1