mysql通过php脚本加载数据infile - 无法正常工作

时间:2014-10-08 05:59:30

标签: php mysql mysqli load-data-infile

我正在尝试使用mysql LOAD DATA LOCAL INFILE通过使用mysqli的php脚本将一些csv数据导入我的mysql数据库。这就是我的sql字符串:

LOAD DATA LOCAL INFILE '/var/www/html/dashmaker/uploads/HHdata.csv' INTO TABLE dashmaker.HHdata FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '\"' LINES TERMINATED BY '\n' IGNORE 1 LINES;

这就是我的php脚本:

$sql = "LOAD DATA LOCAL INFILE '/var/www/html/dashmaker/uploads/HHdata.csv'
       INTO TABLE dashmaker.HHdata
       FIELDS TERMINATED BY ','
       OPTIONALLY ENCLOSED BY '\"' 
       LINES TERMINATED BY '\n' 
       IGNORE 1 LINES;";

$con=mysqli_connect("localhost","[user]","[password]","[database]");
// Check connection
if (mysqli_connect_errno()) {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
};

$result = mysqli_query($sql, $con);

if (mysql_affected_rows() == 1) {
  $message = "The data was successfully added!";
} else {
  $message = "The user update failed: ";
  $message .= mysql_error(); 
};

echo $message;

mysqli_close($con);

我发现我需要将mysql my.cnf设置为在[mysql]和[mysqld]下包含local-infile - 所以我已经这样做了。

当我通过shell运行sql查询时,它可以工作。当我尝试通过php脚本时,我现在得到的错误消息($ message)说:

The user update failed: Access denied for user ''@'localhost' (using password: NO) 

一个奇怪的是它在@'localhost'之前没有显示任何用户名。无法理解为什么。除此之外,我使用相同的连接设置使用PHP脚本从数据库运行常规SELECT查询。用户还具有FILE权限。

我已经进行了广泛的搜索,但没有发现可以解释发生了什么的任何事情。任何建议都将不胜感激。

1 个答案:

答案 0 :(得分:7)

您在几个实例中将MySQL API与mysql_mysqli_函数混合在一起。

  • mysql_affected_rows()
  • mysql_error()

他们混在一起;仅使用mysqli_

另外,你没有在[user]等使用括号,是吗?那就是MSSQL语法,删除它们。

另外,在mysqli_中,首先是数据库连接,将这些$result = mysqli_query($sql, $con);反转为$result = mysqli_query($con, $sql);

$sql = "LOAD DATA LOCAL INFILE '/var/www/html/dashmaker/uploads/HHdata.csv'
       INTO TABLE dashmaker.HHdata
       FIELDS TERMINATED BY ','
       OPTIONALLY ENCLOSED BY '\"' 
       LINES TERMINATED BY '\n' 
       IGNORE 1 LINES;";

$con=mysqli_connect("localhost","user","password","database");
// Check connection
if (mysqli_connect_errno()) {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
};

$result = mysqli_query($con, $sql);

if (mysqli_affected_rows($con) == 1) {
  $message = "The data was successfully added!";
} else {
  $message = "The user update failed: ";
  $message .= mysqli_error($con); 
};

echo $message;
mysqli_close($con);