MySQL PDO中的IGNORE 1 LINES PHP命令行不起作用

时间:2015-04-24 21:04:21

标签: php mysql csv pdo

我通过命令行使用PHP脚本通过PDO语句将CSV文件加载到MySQL中。导入本身成功执行...除了IGNORE 1 LINES

没有忽略第一行

CSV文件:http://federalgovernmentzipcodes.us/free-zipcode-database.csv

(为简洁起见,删除了错误检查,为完整性而留下了完整的SQL)

<?php //import_zips.php

$db_host        = 'localhost';
$db_user        = 'dbuser';
$db_pass        = 'dbpass';
$db_name        = 'dbname';
$input_file     = "free-zipcode-database.csv";
$fieldseperator = ",";
$lineseperator  = "\n";
$fieldsenclosed = '"';
$test_table     = "test_zipcodes";

if(!file_exists($input_file)) {
  die("File not found.");
}

$pdo = new PDO("mysql:host=$db_host;dbname=$db_name", $db_user, $db_pass,
  array(
    PDO::MYSQL_ATTR_LOCAL_INFILE => true,
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
  )
);

$pdo->exec("DROP TABLE IF EXISTS ".$test_table);

$pdo->exec("CREATE TABLE `".$test_table."` (`id` int(11) unsigned NOT NULL AUTO_INCREMENT, `zipcode` int(11) DEFAULT NULL, `type` varchar(10) DEFAULT NULL, `city` varchar(30) DEFAULT NULL, `state` varchar(2) DEFAULT NULL, `location_type` varchar(20) DEFAULT NULL, `lat` double DEFAULT NULL, `lon` double DEFAULT NULL, `xaxis` double DEFAULT NULL, `yaxis` double DEFAULT NULL, `zaxis` double DEFAULT NULL, `worldregion` char(2) DEFAULT NULL, `country` char(2) DEFAULT '', `location_text` varchar(40) DEFAULT NULL, `location` varchar(60) DEFAULT NULL, `decommisioned` char(5) DEFAULT NULL, `tax_returns_filed` bigint(20) DEFAULT NULL, `estimated_population` bigint(20) DEFAULT NULL, `total_wages` bigint(20) DEFAULT NULL, PRIMARY KEY (`id`)) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;");

try {
  $affectedRows = $pdo->exec("
  LOAD DATA LOCAL INFILE ".$pdo->quote($input_file)." INTO TABLE `$test_table`
    FIELDS TERMINATED BY ".$pdo->quote($fieldseperator)." OPTIONALLY ENCLOSED BY ".$pdo->quote($fieldsenclosed)."
    LINES TERMINATED BY ".$pdo->quote($lineseperator))." IGNORE 1 LINES";
  echo "Loaded a total of $affectedRows records.\n";
} catch (PDOException $e) {
  die($e->getMessage()."\n");
}

脚本成功执行(副作用为IGNORE 1 LINES附加到$affectedRows。)

$ php import_zips.php
Loaded a total of 81831 IGNORE 1 LINES records.

问题是CSV的第一行没有被忽略,最终会出现在表格中。基本上,IGNORE 1 LINES被忽略了。

我现在有一个解决方法(手动删除CSV的第一行),但希望有一个更好的解决方案,以便如何使其正常工作。

PHP版

PHP 5.5.23 (cli) (built: Mar 23 2015 01:47:37)

MySQL版

mysql  Ver 14.14 Distrib 5.5.9, for osx10.6 (i386) using readline 5.1

在Mac OS X 10.10.3上运行

1 个答案:

答案 0 :(得分:1)

校正:

$affectedRows = $pdo->exec("
LOAD DATA LOCAL INFILE ".$pdo->quote($input_file)." INTO TABLE `$test_table`
FIELDS TERMINATED BY ".$pdo->quote($fieldseperator)." OPTIONALLY ENCLOSED BY ".$pdo->quote($fieldsenclosed)."
LINES TERMINATED BY ".$pdo->quote($lineseperator)." IGNORE 1 LINES");