如何使用php上传表单多个字段中的多个文件

vngu2lb8  于 2021-06-15  发布在  Mysql
关注(0)|答案(1)|浏览(318)

我有一个表单,其中20多个字段是文件类型,每个字段有多个附件。因此,我如何上传多个文件,每个领域和存储到mysql数据库的文件url。
我做了一些类似于一个领域的多重附加。创建了两个表,其中tablea有表单数据,tableb有文件url和table1父项id。
但我如何处理20+字段与多个附件。有可能吗?提前谢谢。

bxgwgixi

bxgwgixi1#

我已经用2个图像(2个输入字段)和1个pdf文件在同一时间设置了一个例子
因此,我假设您的html标记中包含所有文件输入,如下所示:

<input type="file" name="PDF">
<input type="file" name="MainImage">
<input type="file" name="SecondImage[]">

在这种情况下,要将上载文件的文件路径插入数据库,应该执行以下操作:

$uploadMainTo = null;
if(isset($_FILES['MainImage'])){
  $main_image_name = $_FILES['MainImage']['name'];
  $main_image_size = $_FILES['MainImage']['size'];
  $main_image_tmp = $_FILES['MainImage']['tmp_name'];
  $uploadMainTo = $uploadLocation.$main_image_name;
  $moveMain = move_uploaded_file($main_image_tmp,$uploadMainTo);
}

$uploadSecondTo = array();
if(count(array_filter($_FILES['SecondImage']))>0){
  foreach(array_filter($_FILES['SecondImage']) as $value){
   $second_image_name = $value['name'];
   $second_image_size = $value['size'];
   $second_image_tmp = $value['tmp_name'];
   $uploadSecondTo[] = $uploadLocation.$second_image_name;
   $moveSecond = move_uploaded_file($second_image_tmp,$uploadSecondTo);
  }
  $uploadSecondTo = implode(',',$uploadSecondTo);
}

$uploadPdfTo = null;
if(isset($_FILES['PDF'])){
  $pdf_name = $_FILES['PDF']['name'];
  $pdf_size = $_FILES['PDF']['size'];
  $pdf_tmp = $_FILES['PDF']['tmp_name'];
  $uploadPdfTo = $uploadLocation.$pdf_name;
  $movepdf = move_uploaded_file($pdf_tmp,$uploadPdfTo);
}

$query = $db->execute("INSERT INTO users (pdf, main_image, second_image) VALUES (?,?,?) WHERE ID = ?", array($uploadPdfTo, $uploadMainTo, $uploadSecondTo, $user_id) );

我只是不确定是否必须用null或'null'初始化$uploadxto变量。如果你有问题,请这样测试。
注意:不要忘记在表单上使用enctype=“multipart/form data”
希望这对你有帮助

相关问题