2016-09-14 220 views
2

我試圖使用LOAD DATA LOCAL INFILE從另一個服務器導入csv文件,但它給了我一個錯誤The user update failed: Can't find file,即使文件存在於給定的路徑中。我也試過LOAD DATA INFILE在PHP中將CSV文件導入到Mysql數據庫中

是否有任何其他方法直接導入CSV文件的文件路徑(不使用任何提交按鈕),dBASE表在MySQL數據庫中,並刪除當前數據,如果有一個新的csv文件上傳?

編輯:我也試過這個PHP腳本,導入CSV文件無任何按鍵,但是csv文件數據無法導入

PHP(第2碼):

$mysqli = new mysqli("localhost", "user", "password", "dbasename"); 
$file = "/var/www/html/files/filename.csv"; 
$handle = fopen($file,'r'); 
while (($data = fgetcsv($handle, 10000, ",")) !== FALSE){ 
    $num = count($data); 
    for ($c=0; $c < $num; $c++){ 
     $col[$c] = $data[$c]; 
    } 

    $col1 = $data[0]; 
    $col2 = $data[1]; 
    $col3 = $data[2]; 
    $col4 = $data[3]; 
    $col5 = $data[4]; 

    // SQL Query to insert data into DataBase 
    $query = "INSERT INTO dbname.tablename(col1,col2,col3,col4,col5) VALUES('".$col1."','".$col2."','".$col3."','".$col4."','".$col5."')"; 
    $mysqli->query($query); 
} 
fclose($handle); 

這裏的的PHP:

$sql = "LOAD DATA LOCAL INFILE 'filename.csv' 
     INTO TABLE dbname.tablename 
     FIELDS TERMINATED BY ',' 
     OPTIONALLY ENCLOSED BY '\"' 
     LINES TERMINATED BY '\n' 
     IGNORE 1 LINES;"; 

$con=mysqli_connect("localhost","user","password","db"); 
// Check connection 
if (mysqli_connect_errno()){ 
    echo "Failed to connect to MySQL: " . mysqli_connect_error(); 
}; 

$result = mysqli_query($con, $sql); 

if (mysqli_affected_rows($con) == 1){ 
    $message = "The data was successfully added!"; 
} else { 
    $message = "The user update failed: "; 
    $message .= mysqli_error($con); 
}; 

echo $message; 
+0

@ e4c5,我並不想導出數據,但將其導入到MySQL數據庫。我不這是重複的 – User014019

回答

0

這已被問及之前回答。使用google更好: Mysql permission errors with 'load data'

您需要授予文件權限給mysql用戶。

+0

我已經在mysql中授予權限,但是同樣的錯誤 – User014019

+0

它是否必須是文件的完整路徑? – systematical

+0

是的,我把文件的完整路徑。無論如何,文件所在的遠程服務器/ ftp沒有mysql/phpmyadmin。還有其他方法可以導入一個csv文件,而無需點擊任何按鈕? – User014019

0

你也可以嘗試使用

$con=mysqli_connect("localhost","user","password","db"); 
$file = fopen("filename.csv","r"); 
while ($data = fgetcsv ($file)){ 
    print_r($data); 
    $sql = 'insert into ...' 
    $result = mysqli_query($con, $sql); 
} 

導入CSV文件

+0

我已經試過,但數據仍然沒有導入 – User014019