提问者:小点点

在Mysql中导入CSV无效


我喜欢写一个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);




?>

共1个答案

匿名用户

您正在执行的查询:

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

适用于检测产品是否存在,然后更新或插入。对于只有一个UPDATE,SELECT并不重要,因为如果你有一个外键,就不会有一个条目WHEREProduct_IDnot IN(SELECTProduct_IDfrom 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;
}