我有需要导入MySQL数据库的CSV文件。我正在使用PHP脚本导入CSV。
脚本工作正常,直到我添加ENCLOSED BY语句,我添加该语句的原因是因为CSV列中的某个值包含带逗号的文本,但该值用引号括起来。
以下是CSV列的示例,其中包含用引号括起的值:
,“1名注册守护者,全程服务历史,中央锁定,电动车窗,电动后视镜,ABS,牵引力控制,气候控制,动力转向,驾驶员安全气囊,乘客安全气囊,侧面安全气囊,巡航控制,警报,防盗器,一半皮革内饰,合金轮“,
以下是我尝试过的脚本:
<?php
$databasehost = "localhost";
$databasename = "import";
$databasetable = "import";
$databaseusername="import";
$databasepassword = "password";
$fieldseparator = ",";
$lineseparator = "\n";
$enclosedbyquote = '"';
$csvfile = "test.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",
$databaseusername, $databasepassword,
array(
PDO::MYSQL_ATTR_LOCAL_INFILE => true,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
)
);
} catch (PDOException $e) {
die("database connection failed: ".$e->getMessage());
}
$pdo->exec("TRUNCATE TABLE `$databasetable`");
$affectedRows = $pdo->exec("
LOAD DATA LOCAL INFILE ".$pdo->quote($csvfile)." REPLACE INTO TABLE `$databasetable`
ENCLOSED BY ".$pdo->quote($enclosedbyquote)."
FIELDS TERMINATED BY ".$pdo->quote($fieldseparator)."
LINES TERMINATED BY ".$pdo->quote($lineseparator)."
IGNORE 1 LINES");
echo "Loaded a total of $affectedRows records from this csv file.\n";
?>
因为我已添加:
$enclosedbyquote = '"';
和
ENCLOSED BY ".$pdo->quote($enclosedbyquote)."
我收到错误:(
知道我做错了什么,任何提示都会非常感激!?
答案 0 :(得分:1)
你应该看看Syntax。你需要先放FIELDS
字。
而不是
ENCLOSED BY ".$pdo->quote($enclosedbyquote)."
FIELDS TERMINATED BY ".$pdo->quote($fieldseparator)."
你应该:
FIELDS ENCLOSED BY ".$pdo->quote($enclosedbyquote)."
TERMINATED BY ".$pdo->quote($fieldseparator)."
答案 1 :(得分:0)
看起来你错过了char附近的引号:
ENCLOSED BY '".$pdo->quote($enclosedbyquote)."'