2017-10-16 99 views
0

我上傳多個文件,並試圖將他們的詳細信息存儲在SQL數據庫,但只有第一個文件上傳,並停止上傳其餘選定的文件。PHP多個文件上傳到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 & file3。只有file1的信息插入到db,但file2 & 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)); 
    } 
} 
+0

看看這是否有幫助。 https://stackoverflow.com/questions/13270210/upload-multiple-files-to-server-and?rq=1 –

+0

echo count的輸出是什麼($ _ FILES ['my_file'] ['name']) )''' –

+0

@WalkerBoh計數是3,我也可以打印所有的文件名和路徑。 –

回答

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"; 
    } 
} 
相關問題