所以,我得到了这个。只是尝试通过PHP PDO驱动程序将csv文件插入MySQL:
<?php
$databasehost = "localhost";
$databasename = "db";
$databasetable = "table";
$socketPath = "/home/mysql/mysql.sock";
$databaseusername="user";
$databasepassword = "pass";
$fieldseparator = ",";
$fieldenclosed = '"';
$lineseparator = "\r\n";
$csvfile = "file.csv";
if(!file_exists($csvfile)) {
die("File not found. Make sure you specified the correct path.");
}
try {
$pdo = new PDO("mysql:host=$databasehost;dbname=$databasename;unix_socket=$socketPath",
$databaseusername, $databasepassword,
array(
PDO::MYSQL_ATTR_LOCAL_INFILE => true,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
)
);
} catch (PDOException $e) {
die("database connection failed: ".$e->getMessage());
}
$affectedRows = $pdo->exec("
LOAD DATA LOCAL INFILE ".$pdo->quote($csvfile)." INTO TABLE `$databasetable`
FIELDS TERMINATED BY ".$pdo->quote($fieldseparator).", ENCLOSED BY ". $pdo->quote($fieldenclosed)."
LINES TERMINATED BY ".$pdo->quote($lineseparator)." IGNORE 1 LINES;");
echo "Loaded a total of $affectedRows records from this csv file.\n";
?>
csv文件是这样的(逗号分隔并用双引号括起来。)
"X410","","4114068500","000010","04/15/2014","04/16/2015"
"X410","","4220521243","000030","04/08/2014","04/08/2015"
"X410","","4130003659","000010","04/02/2014","04/05/2014"
"X410","","4220524277","000010","04/08/2014","04/08/2015"
"X410","","4114038136","000010","04/07/2014","04/07/2015"
"X410","","4130003594","000110","03/14/2014","03/14/2015"
"X410","","4130003675","000010","04/04/2014","04/04/2015"
"X410","","4130003623","000010","03/12/2014","03/12/2015"
"X410","","4130003679","000010","04/09/2014","04/09/2015"
"X410","","4130003679","000020","04/09/2014","04/09/2015"
ENCLOSED BY
部分是给我带来麻烦的部分,我已经完成了我的作业并尝试了$fieldenclosed = '\"\"'
,$fieldenclosed = "\"\""
,有$pdo->quote($fieldenclosed)
和其他任何其他人PHP Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ' ENCLOSED BY '"'
LINES TERMINATED BY '\r\n' IGNORE 1 LINES' at line 2' in /root/csvUpload.php:32
奇怪的concat stuf我已经或者在其他主题中发现了类似的问题。
MySQL抛出此错误:
{{1}}
我在CentOS 6.4服务器上运行MySQL 5.1。
有什么想法吗?
答案 0 :(得分:1)
ENCLOSED BY
之前不应该有逗号。它应该是:
$fieldenclosed = '"';
只是一个引用 - 它应该是在该字段的开头和结尾处的字符。
您也错误输入了变量名称,没有结束字符串并在调用$pdo->quote
时连接。
$affectedRows = $pdo->exec("
LOAD DATA LOCAL INFILE ".$pdo->quote($csvfile)." INTO TABLE `$databasetable`
FIELDS TERMINATED BY ".$pdo->quote($fieldseparator)." ENCLOSED BY ".$pdo->quote($fieldenclosed)."
LINES TERMINATED BY ".$pdo->quote($lineseparator)." IGNORE 1 LINES;");