dongling0519 2018-12-17 10:54
浏览 152

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

I have a form where 20+ fields are file type and each field have multiple attachment. So how can i upload multiple files each of the field and store the files url into mysql database.

I have did something like multiple attachment of a field. Created 2 tables where tableA has form data and tableB have files url with table1 parent_id.

But how can i handle 20+ field with multiple attachment. Is it possible? Thanks in advance.

  • 写回答

1条回答 默认 最新

  • dongzongzi0379 2018-12-17 11:00
    关注

    I have set an example with 2 images (2 input fields) and 1 pdf file at the same time

    So, I assume that you will have all the file inputs in your HTML markup, something like this:

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

    In this case, to insert the file path of the uploaded file to the database, something like this should work:

    $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) );
    

    I'm just not sure if i have to initialize the $uploadXTo variables with null or 'NULL'. If you have problems please test this way.

    NB Don't forget to use enctype="multipart/form-data" on your form

    Hope this will help you

    评论

报告相同问题?

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?