即使我可以从 cli 客户端使用,为什么我不能将 LOAD DATA LOCAL 与 PDO 一起使用?

2021-12-26 00:00:00 ubuntu php mysql pdo load-data-infile

我最近将我的 Ubuntu 10.04 开发服务器升级到 14.04.它实际上是全新安装.PHP 版本是 5.4.15,现在是 PHP 5.5.9.MySQL 从 5.1.67 到 5.5.37.

I recently upgraded my Ubuntu 10.04 dev server to 14.04. It is actually a fresh install. PHP version was 5.4.15, and is now PHP 5.5.9. MySQL went from 5.1.67 to 5.5.37.

我正在尝试在新服务器上加载本地数据文件.它可以使用本地 mysql cli 客户端运行命令.使用 PDO 执行时不起作用:

I am trying to LOAD LOCAL DATA INFILE on a new server. It works running the command using the local mysql cli client. It does not work when executing using PDO:

PHP Fatal error:  Uncaught exception 'PDOException' with message 'SQLSTATE[42000]: Syntax error or access violation: 1148 The used command is not allowed with this MySQL version' in /home/ubuntu/mysqltest.php:21
Stack trace:
#0 /home/ubuntu/mysqltest.php(21): PDO->exec('LOAD DATA LOCAL...')
#1 {main}
  thrown in /home/ubuntu/mysqltest.php on line 21

产生错误的代码:

ini_set('mysql.allow_local_infile', 1);
echo "mysql.allow_local_infile: ".ini_get("mysql.allow_local_infile").PHP_EOL;

$options = array(PDO::MYSQL_ATTR_LOCAL_INFILE => 1);
$db = new PDO("mysql:host=$dbHost;dbname=$dbName;charset=utf8", $dbUser, $dbPassword, $options);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$db->exec("CREATE TEMPORARY TABLE tmp_table ( id INT(4), col1 varchar(128) ) ENGINE MYISAM");

$loadSQL = <<<'EOT'
LOAD DATA LOCAL INFILE '/tmp/test.csv' INTO TABLE `tmp_table` FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"' ESCAPED BY '\' LINES TERMINATED BY '
' IGNORE 1 LINES (id, col1)
EOT;

$db->exec($loadSQL);

目前为解决问题采取的步骤:

Steps taken so far to address problem:

  • 我已将 local-infile = 1 添加到/etc/mysql/my.cnf 的 [mysql] 和 [mysqld] 部分
  • 我已经检查过 mysql.allow_local_infile = On 在/etc/php5/cli/php.ini 中.
  • DB 用户是 root 用户,因此拥有所有权限.
  • /tmp/test.csv 确实存在并且用户对其拥有完全权限.

推荐答案

这是 php 中的一个错误.请参阅https://bugs.php.net/bug.php?id=68226 用于解释和解决方法.

This is a bug in php. Please see https://bugs.php.net/bug.php?id=68226 for explanation and workaround.

相关文章