PHP多个文件上传到SQL,只上传第一个文件

时间:2017-10-16 16:21:57

标签: php sql-server

我上传多个文件并尝试将其详细信息存储在SQL数据库中,但只上传了第一个文件并停止上传其余所选文件。

以下是我的HTML以获取表单中的多个文件:

<form method="post" enctype="multipart/form-data">
   <input name="my_file[]" type="file" id="userfile" multiple> 
   <button type="submit" name="btn-upload">upload</button>
</form>

我的PHP代码,用于上传文件信息,如名称和类型:

if(isset($_POST['btn-upload'])){    
   if (($_FILES['my_file']['name']!="")){
      for ($i = 0 ; $i < count($_FILES['my_file']['name']) ; $i++){ 
         $target_dir = "upload_test/";
         $file = $_FILES['my_file']['name'][$i];
         $path = pathinfo($file);
         $ext = $path['extension'];
         $target_dir = $target_dir.basename($file);
         $user = "xxx";

         if(insertFile_info(basename($file) , $target_dir, $user, $ext, $conn)){
            echo "Insert file success";
         }else{
            echo "Insert Failed";
         }
      }
   }
}

例如,如果我选择file1file2&amp; file3。只有file1的信息被插入到数据库中,但是file2&amp; file3根本没有插入数据库。

这里的问题是什么?

这是我的插入方法:

function insertFile_info ($file_name , $path, $username, $type, $conn){
   $sql = "INSERT INTO URL (file_name, path, username, type) VALUES (?, ?, ?, ?);";
   $params = array($file_name , $path, $username, $type);
   if (sqlsrv_query( $conn, $sql, $params) === TRUE) {
       // success 
   } else {
      die( print_r( sqlsrv_errors(), true));
   }
}

1 个答案:

答案 0 :(得分:0)

听起来你的问题已经解决了,但无论如何我都会发布你的代码建议。准备查询会占用大量开销;如果您要多次执行查询,则应该只准备一次。

// initialize the variables
$params = array($file = "", $target_dir = "", $user = "", $ext = "");
$sql = "INSERT INTO URL (file_name, path, username, type) VALUES (?, ?, ?, ?);";
// prepare the statement, it's now bound to the variables
$stmt = sqlsrv_prepare($conn, $sql);

if (isset($_POST['btn-upload'] && count($_FILES['my_file']['name'])) {
    foreach ($_FILES['my_file']['name'] as $i => $file) {
        $target_dir = "upload_test/$file";
        $user = "xxx";
        $ext = pathinfo($file, PATHINFO_EXTENSION);
        $file = basename($file);
        // now execute the query with the value in the variables
        if (!sqlsrv_execute($stmt)) {
            echo "Insert file failure";
            // of course, this is just for testing...
            print_r(sqlsrv_errors());
            die();
        }
        echo "Insert file success";   
    }
}