2014-04-18 21:45
浏览 45


So, I got this. Just trying to insert a csv file into a MySQL through PHP PDO driver:

$databasehost = "localhost";
$databasename = "db";
$databasetable = "table";
$socketPath = "/home/mysql/mysql.sock";
$databasepassword = "pass";
$fieldseparator = ",";
$fieldenclosed = '"';
$lineseparator = "
$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,
            PDO::MYSQL_ATTR_LOCAL_INFILE => true,
} 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.


The csv file is something like this(comma separated and enclosed by double quotes).


THe ENCLOSED BY part is the one that's giving me trouble, I've done my homework and tried $fieldenclosed = '\"\"', $fieldenclosed = "\"\"", with and withouth the $pdo->quote($fieldenclosed) and any other weird concat stuf I've though of or found out in other topics with similar issues.

MySQL throws this error:

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 '"'
' IGNORE 1 LINES' at line 2' in /root/csvUpload.php:32

Im running MySQL 5.1 in a CentOS 6.4 server.

Any ideas?

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

1条回答 默认 最新

相关推荐 更多相似问题