通过csv文件更新MySQL中的表

时间:2017-03-22 08:50:00

标签: php mysql csv

我必须按cscart_products文件csv更新表output.csv

我创建了一个临时表(your_temp_table)并使用INNER JOIN命令更新了cscart_products表(product_codeamount)。

执行以下代码时,MySQL报告此错误:

  

用户更新失败:您的SQL语法出错;检查与您的MySQL服务器版本相对应的手册,以便在your_temp_table.amount = cs'上使用接近' UPDATE cscart_products INNER JOIN your_temp_table的正确语法。在第6行

有错误吗? SQL语法错了吗?

<?php
$sql = "LOAD DATA INFILE 'output.csv'
       INTO TABLE your_temp_table
       FIELDS TERMINATED BY ','
    (product_code, amount);

UPDATE cscart_products
INNER JOIN your_temp_table on your_temp_table.amount = cscart_products.amount
SET cscart_products.product_code = your_temp_table.product_code;";

$con=mysqli_connect("localhost","xxx","xxxx","xxxx");
// Check connection
if (mysqli_connect_error()) {
  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);
?>

1 个答案:

答案 0 :(得分:3)

在mysqli中,它们应该作为两个查询执行

$sql = "LOAD DATA INFILE 'output.csv'
       INTO TABLE your_temp_table
       FIELDS TERMINATED BY ','
    (product_code, amount)";

$sql2 = "UPDATE cscart_products
INNER JOIN your_temp_table on your_temp_table.amount = cscart_products.amount
SET cscart_products.product_code = your_temp_table.product_code";


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

或者,您必须使用multi_query