如何上传由jquery创建的多个文件字段:PHP和MYSQLi

时间:2017-06-07 10:02:13

标签: javascript php jquery mysql mysqli

我希望用户能够单独上传多个文件。使用jquery动态添加文件字段。如何使用php将这些文件上传到mysqli,以便其他人能够使用相应的文件名查看上传的文件?我希望这是有道理的

< script >
  $(document).ready(function() {
    var i = 1;
    $('#add_input').click(function() {
      i++;
      $('#dynamic').append('<tr id="row' + i + '"><td><input type="file" name="file[]" placeholder="choose document" required/></td><td><input type="text" name="file_name[]" placeholder="enter file name" required/></td><td><button type="button" name="remove" id="' + i + '" class="btn_remove">Remove</button></td></tr>');
    });
    $(document).on('click', '.btn_remove', function() {
      var button_id = $(this).attr("id");
      $('#row' + button_id + '').remove();
    });
  }); <
/script>
<form enctype="multipart/form-data" method="post" name="add_me" id="add_me" action="inserrt.php" autocomplete="off">
  <table id="dynamic">
    <td><input type="file" name="file[]" placeholder="choose document" required/></td>
    <td><input type="text" name="file_name[]" placeholder="enter file name" required/></td>
    <td><button type="button" name="add" id="add_input">Add</button></td>
  </table>
  <form>

这个php代码只会上传多个文件,并且只使用mysqli在数据库中插入1个文件路径

 $upload_directory = 'uploads/';
     $x=0;
          echo "</div>Uploaded Files:</div>";
          foreach ( $_FILES['file']['name'] AS $key => $value ){
               echo "<div>{$value}</div>";
               //Move file to server directory

               move_uploaded_file($_FILES["file"]["tmp_name"][$x], $upload_directory . $_FILES["file"]["name"][$x]);
               $x++;
             }
             foreach ( $_FILES['file']['name'] AS $key => $value ){
               $x=0;
               $number = count($_FILES["file"]);
               for($x; $x<$number; $x++){
               $fpath = mysqli_real_escape_string($conn, $upload_directory . $_FILES["file"]["name"][$x]);
               $fname = mysqli_real_escape_string($conn, $_FILES["file"]["name"][$x]);
               $sql= "INSERT INTO files (file_path,file_name,applicant_id,facility)
               VALUES
               ('$fpath','$fname','2','lee radiology')";
               $x++;

               if (!mysqli_query($conn,$sql)){
                 die('Error: ' . mysqli_error($conn));
                 }
                   mysqli_close($conn);

                  exit;

0 个答案:

没有答案