我正在尝试将CSV文件导入MySql数据库并且其工作除了一件事 - 其中一个字段来自自由格式文本字段,并且当用户输入逗号时会导致问题。然而,在这一个字段中有一个“数据的开头和结尾。我正在使用下面的代码尝试将其更改为空字段,但我无法让它工作 - 我必须遗漏一些东西,盯着看它连续几个小时没有帮助。在此先感谢!!
代码:
<?php
require('phpsqlajax_dbinfo.php');
$databasehost = $db_host;
$databasename = $db_name;
$databasetable = "tbl_csvImport";
$databaseusername=$db_user;
$databasepassword = $db_pass;
$fieldseparator = ",";
$lineseparator = "\n";
$csvfile = "doecsv.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());
}
$affectedRows = $pdo->exec("
LOAD DATA LOCAL INFILE ".preg_replace('/"[^"]+"/','',$pdo->quote($csvfile))." INTO TABLE `$databasetable`
FIELDS TERMINATED BY ".$pdo->quote($fieldseparator)."
LINES TERMINATED BY ".$pdo->quote($lineseparator))
?>
答案 0 :(得分:2)
你需要告诉MySQL这些字段可以用引号括起来。
LOAD DATA LOCAL INFILE 'yourFile.csv' INTO TABLE `yourTable`
FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"'
LINES TERMINATED BY '\n'