2016-11-16 61 views
-1

我嘗試上傳一個Excel工作表(CSV)到我的數據庫在PHP,但它表明成功。但是,我去mysql確認,我注意到只有Excel表中的最後一行顯示在MySQL表中。請需要幫助。我不知道還有什麼要做。上傳Excel工作表在PHP到數據庫只給最後一行

<?php 
include ("base.php"); 

if (isset($_POST['submit'])) { 

    //inserting into db 
    //getting the file and inserting it in db 
    $file = $_FILES['file']['tmp_name']; 
    $handle = fopen($file, "r"); 
    $tot = 0; 
    while(($data = fgetcsv($handle, 1000, ",")) !== FALSE) { 

     for ($c=0; $c < 1; $c++) { 

      //only run if the first column if not equal to name 
      if ($data[0] != 'name') { 

       $name = mysqli_real_escape_string($con, $data[0]); 
       $reg_no = mysqli_real_escape_string($con, $data[1]); 
       $lab = mysqli_real_escape_string($con, $data[2]); 
       $test = mysqli_real_escape_string($con, $data[3]); 
       $exam = mysqli_real_escape_string($con, $data[4]); 
       $total = mysqli_real_escape_string($con, $data[5]); 
       $grade = mysqli_real_escape_string($con, $data[6]); 
       $remark = mysqli_real_escape_string($con, $data[7]); 

       //inserting into db 
       $sql = "INSERT INTO imt303 (name, reg_no, lab, test, exam, total, grade, remark) 
         VALUES ('$name', '$reg_no', '$lab', '$test', '$exam', '$total', '$grade', '$remark')"; 
      } 

     //incrementing  
     $tot++; 
     } 
    } 

    if (mysqli_query($con, $sql)) { 

     echo '<script type="text/javascript">alert("Uploaded Successfully!");</script>'; 
    } else { 

     echo '<script type="text/javascript">alert("There is a problem uploading file!");</script>'; 
    } 
} 

?> 

<html> 

<form method="POST" action="test.php" enctype="multipart/form-data"> 
    <input type="file" name="file"> 
    <input type="submit" name="submit" value="Submit"> 
</form> 

</html> 
+0

你可以使用加載數據infile。 – e4c5

+3

你是否明白在每個'while'迭代中你__overwrite__'$ sql'? –

+0

'mysqli_query($ con,$ sql)'應該在循環體中 – cske

回答

0

您正在重寫$ sql值。 $ sql值是分配給最後一個查詢的值。要麼你在while循環中包含查詢(不能重新計算),要麼你創建一個迭代和插入的$ sql []數組,或者我要做的最後一個表單,創建一個帶插入值的主$ sql,並將循環中的值連接起來製作一個大插頁。

+0

我該如何做所有這些?我仍然是一個學習者 – Emmajiugo

+0

非常感謝您的幫助。現在完美運作 – Emmajiugo

相關問題