LOAD DATA INFILE - FIELDS TERMINATED错误

时间:2014-01-20 03:10:24

标签: php mysql

我有以下加载数据infile查询:

LOAD DATA INFILE $csv INTO TABLE safety_quiz FIELDS TERMINATED BY ',' LINES TERMINATED BY '\r\n' (first_name, last_name, person_id, quiz_result)

这会产生以下错误:

  

您的SQL语法有错误;检查与您的MySQL服务器版本对应的手册,以便在' ../ import / import_20_01_2014.csv附近使用正确的语法INTO TABLE safety_quiz FIELDS TERMINATED BY',' '在第1行

csv格式为:

Bob,Smith,123456789,100
Fred,Jones,987654321,100

表结构是:

CREATE TABLE `safety_quiz` (
  `safety_quiz_pk` int(8) NOT NULL AUTO_INCREMENT,
  `first_name` varchar(80) NOT NULL,
  `last_name` varchar(80) NOT NULL,
  `person_id` varchar(9) NOT NULL,
  `quiz_result` varchar(10) NOT NULL,
  PRIMARY KEY (`safety_quiz_pk`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

我已经查看了同一问题的其他stackoverflow问题,但我无法看到错误的位置......

更新

完整代码:

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

if(!empty($_FILES["file"]["tmp_name"])){

$type = explode(".",$_FILES['file']['name']);

if(strtolower(end($type)) == 'csv'){

$path = '../import/';   
$file_name = 'import_' . date('d_m_Y') . '.csv';
move_uploaded_file($_FILES["file"]["tmp_name"], $path . $file_name);

} else {
    $message = 'Only csv files can be uploaded.';   
}
} else {
    $message = 'You need to attach a csv file.';    

}

$csv = $path . $file_name;

$query = "LOAD DATA INFILE '$csv' INTO TABLE safety_quiz FIELDS TERMINATED BY ',' LINES TERMINATED BY '\r\n' (first_name, last_name, person_id, quiz_result)";
$result = mysql_query($query, $connection) or die(mysql_error());
}

工作代码

看起来csv的路径必须是绝对的(不知道为什么......),但这样做有效:

$csv = '/var/www/html/labs/import/' . $file_name;

$query = "LOAD DATA INFILE '$csv' INTO TABLE safety_quiz FIELDS TERMINATED BY ',' LINES TERMINATED BY '\n' (first_name, last_name, person_id, quiz_result)";
$result = mysql_query($query, $connection) or die(mysql_error());
}

1 个答案:

答案 0 :(得分:2)

以下示例来自位于页面底部附近的http://dev.mysql.com/doc/refman/5.5/en/load-data.html

"LOAD DATA INFILE '$myFile'" . " INTO TABLE test FIELDS TERMINATED BY '|' LINES TERMINATED BY '\n' 

它显示了用引号括起来的文件变量。

尝试以下方法:

LOAD DATA INFILE '$csv' INTO TABLE safety_quiz FIELDS TERMINATED BY ',' LINES TERMINATED BY '\r\n' (first_name, last_name, person_id, quiz_result)

由于Ohgodwhy stated in a comment$csv变量未正确封装,因此按字面解释。

或封装在带点的单引号和双引号中:

LOAD DATA INFILE '".$csv."'

借鉴this answer on SO