加载数据infile不起作用

时间:2015-12-16 13:42:48

标签: php csv

我正在尝试通过csv文件批量上传。我的csv文件位于webroot / CSV / data.csv中。数据如下:

name,email
santo, abc@gmail.com

我的代码:

$sql = "LOAD DATA INFILE '$filepath'
    INTO TABLE customers
    FIELDS TERMINATED BY ','
    OPTIONALLY ENCLOSED BY '\"' 
    LINES TERMINATED BY ',,,\\r\\n'
    IGNORE 1 LINES 
    (name, email)";
    $this->Customer->query($sql);

这里

$filepath = WWW_ROOT . 'CSV' . DS.'data.csv';

获取错误:

C:\server\mysql\data\serverhtdocsdemo-home25appwebrootCSVdata.csv' not found (Errcode: 2 "No such file or directory")

我检查它存在的文件,sql中的文件位置似乎没问题:

SQL Query: LOAD DATA INFILE 'C:\server\htdocs\demo-home25\app\webroot\CSV\data.csv' INTO TABLE customers FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"' LINES TERMINATED BY ',,,\r\n' IGNORE 1 LINES (name, email)

我的代码有什么问题?

2 个答案:

答案 0 :(得分:1)

你试过使用“LOAD DATA LOCAL INFILE”?

LOAD DATA LOCAL INFILE 'abc.csv' INTO TABLE abc
FIELDS TERMINATED BY ',' 
ENCLOSED BY '"' 
LINES TERMINATED BY '\r\n'
IGNORE 1 LINES
(col1, col2, col3, col4, col5...);

在你的情况下:

$sql = "LOAD DATA LOCAL INFILE '$filepath'
    INTO TABLE customers
    FIELDS TERMINATED BY ','
    OPTIONALLY ENCLOSED BY '\"' 
    LINES TERMINATED BY ',,,\\r\\n'
    IGNORE 1 LINES 
    (name, email)";
    $this->Customer->query($sql);

“如果指定了LOCAL,则文件由客户端主机上的客户端程序读取并发送到服务器。”来自Documentation

https://stackoverflow.com/a/14133740/2925795

中回答

答案 1 :(得分:0)

我有同样的问题。有时,您的mysql服务器和客户端会以不同的方式理解文件位置。

LOCAL修饰符(LOAD DATA LOCAL INFILE)添加到您的查询

$sql = "LOAD DATA LOCAL INFILE '$filepath'
INTO TABLE customers
FIELDS TERMINATED BY ','
OPTIONALLY ENCLOSED BY '\"' 
LINES TERMINATED BY ',,,\\r\\n'
IGNORE 1 LINES 
(name, email)";
$this->Customer->query($sql);