2016-11-29 124 views
-1

我想創建一個簡單的表單上傳CSV文件到MySql使用MySQLi面向對象。與數據庫的連接工作正常,但由於某種原因,我還沒有弄清楚它不會將CSV文件中的數據插入到數據庫中。CSV文件上傳到MySql

$servername = "localhost"; 
$username = "user_name"; 
$password = "password"; 
$dbname = "db_name"; 

// Create connection 
$conn = new mysqli($servername, $username, $password, $dbname); 

// Check connection 
if ($conn->connect_error) { 
    die("Connection failed: " . $conn->connect_error); 
} 

if(isset($_POST["submit"])) { 
    if($_FILES['file']['name']) { 
     $filename = explode(".", $_FILES['file']['name']); 
     if ($filename[1] == 'csv') { 

      $handle = fopen($_FILES['file']['tmp_name'], "r"); 
      while($data = fgetcsv($handle)) { 
       $user_id = mysqli_real_escape_string($conn, $data[1]); 
       $name = mysqli_real_escape_string($conn, $data[2]); 
       $last_mod = mysqli_real_escape_string($conn, $data[3]); 

       $sql="INSERT into user (user_id, name, last_mod) VALUES ('$user_id', '$name', '$last_mod')"; 
       if (!mysqli_query($con,$sql)) { 
       die('Error: ' . mysqli_error($con)); 
       } 
       echo "1 record added"; 
      } 

      $conn->close(); 
     } 
    } 

} 

<form action="index.php" method="POST" enctype="multipart/form-data" name="beer"> 
<div class="form-group"> 
<label for="file">Select your file:</label> 
<input name="file" type="file"> 
</div> 
<div class="checkbox"> 
<label><input type="checkbox">I agree!</label> 
</div> 
<button type="submit" class="btn btn-default">Upload</button> 
</form> 
+0

我可能會錯過一些東西,但是你在哪裏設置'$ row'? – andrewsi

+0

@andrewsi ...對不起,這是舊版本,我已將其更改爲「數據」 – user3767773

+1

「LOAD DATA INFILE」有什麼問題? – e4c5

回答

-1
  1. 請檢查文件類型。它必須是.csv。
  2. 請檢查您的csv文件並刪除您在其中編寫列名的行。