【问题标题】:Import CSV in Mysql does not work在 Mysql 中导入 CSV 不起作用
【发布时间】:2016-02-17 19:43:31
【问题描述】:

我喜欢编写一个 csv 导入/更新到我的 Mysql 数据库,但它不起作用。我没有收到任何错误消息。

谁能帮我找出错误或我的脚本有什么问题。

// set local variables
$connect = mysql_connect("localhost","root","") or die('Could    not connect: ' . mysql_error());
$handle = fopen("imptest.csv", "r");

// connect to mysql and select database or exit 
mysql_select_db("shoptest1", $connect);

    while($data = fgetcsv($handle, 30000, ';')) //Jede Zeile durchgehen
     {
     $Product_ID=$data[0];
     $field=$data[1];

     $query = 'SELECT Product_ID FROM testprod';
if (!$result = mysql_query($query)) {
continue;
} if ($line = mysql_fetch_array($result, MYSQL_ASSOC)) {

// entry exists update
$query = "UPDATE ps_product_lang SET custom_field ='$field' WHERE id_product = '$Product_ID'";


mysql_query($query);
if (mysql_affected_rows() <= 0) {
echo "kein update";
// no rows where affected by update query
}
} else {
echo "kein eintrag";
// entry doesn't exist continue or insert...
}

mysql_free_result($result);
}

fclose($handle);
mysql_close($connect);




?>

【问题讨论】:

  • 停止使用已弃用的mysql_* API。使用mysqli_PDO
  • 您从不检查错误,因此您不会收到错误消息
  • 您正在选择testprod 中的所有行,并且continue 出错,或者,如果该表包含至少1 个产品ID,则更新另一个表ps_product_lang 中可能或可能的行不存在。

标签: mysql csv import


【解决方案1】:

您正在执行的查询:

SELECT Product_ID FROM testprod
UPDATE nl_product_lang SET custom_field = ? WHERE Product_ID = ?

适用于检测产品是否存在,然后是 UPDATE 或 INSERT。仅对于 UPDATE,SELECT 无关紧要,因为不会有条目 WHERE Product_ID NOT IN (SELECT Product_ID FROM testprod) - 如果您有外键。

以下是如何使用 PDO 执行此操作的示例。

list( $SQLDSN, $SQLUSER, $SQLPASS ) = [ 'mysql:dbname=shoptest1', 'root', '' ];

$db = new PDO( $SQLDSN, $SQLUSER, $SQLPASS, [      
    PDO::MYSQL_ATTR_INIT_COMMAND  => 'SET NAMES utf8',
    PDO::ATTR_ERRMODE             => PDO::ERRMODE_EXCEPTION
] );

$ids = $db->query( "SELECT Product_ID from testprod" )->fetchAll( \PDO::FETCH_COLUMN, 0 );

while ( list( $Product_ID, $field ) = fgetcsv(...) )
    if ( in_array( $Product_ID, $ids ) )
        query( $db, "UPDATE ps_product_lang SET custom_field = ? WHERE Product_ID = ?",
          [ $field, $Product_ID ]
        );
    else
        trigger_warning( "unknown product $Product_ID" );

function query( $db, $sql, $args = null ) {
    $sth = $db->prepare( $sql );
    $sth->execute( $sql );   
    return $sth;
}

【讨论】:

    猜你喜欢
    • 2011-12-20
    • 2013-01-08
    • 1970-01-01
    • 2017-01-21
    • 2016-08-15
    • 2016-11-23
    • 1970-01-01
    • 2023-03-25
    • 2012-11-18
    相关资源
    最近更新 更多