0

试图拼凑 fgetcsv 问题和答案以获得我需要的地方,但没有掌握足够的基础知识来获得我需要的结果。制表符分隔文件示例....

╔══════════════╦════════════╦═══════╦══════════╗
║     sku      ║    asin    ║ price ║ quantity ║
╠══════════════╬════════════╬═══════╬══════════╣
║ 00-1IAB-H5E9 ║ B008S0TEFQ ║ 5.00  ║        1 ║
║ 00-BOXP-HDX4 ║ B00BP9N4JO ║ 20.00 ║        1 ║
╚══════════════╩════════════╩═══════╩══════════╝

我需要根据 sku 用新数量更新数据库。找到了很多类似的答案,但不完全是我需要的。价格和 ASIN 被忽略。这是我到目前为止相关部分的代码。

$fin = fopen('qtyme.txt','r') or die('cant open file');
$link = mysql_connect('xxxx.com', 'xxxx', 'xxxx');
If (!$link) {
    die ('Could not connect: ' . mysql_error());
}
@mysql_select_db('xxxx') or die ('Unable to select database');
echo "Connection succeeded, starting processing..... <br />\n";
while (($data=fgetcsv($fin,r,"/t"))!==FALSE) {
    $query = "UPDATE products SET products_quantity = '".$data[3]."' WHERE products_sku = '".$data[0]."'";
    mysql_query($query);
    echo ($query) . "<br />\n";
    }
fclose($fin);
mysql_close();

显然我不知道我在做什么,但似乎我的问题在于定义列以提取正确的数据以进行 UPDATE。

帮助?

最终解决方案:非常感谢您的帮助!

$link = mysql_connect('xxxx', 'xxxx', 'xxxx'); If (!$link) {
    die ('Could not connect: ' . mysql_error()); } @mysql_select_db('xxxx') or die ('Unable to select database');

$sql = "TRUNCATE TABLE `tmpStock`"; mysql_query($sql); echo "Temporary Table Deleted...<br>";

$result = mysql_query("LOAD DATA LOCAL INFILE 'qtyme.txt' INTO TABLE tmpStock FIELDS TERMINATED BY '\t' ENCLOSED BY '\"' LINES TERMINATED BY '\n'")or die ('Error: '.mysql_error ()); echo "Temporary Data Uploaded and Inserted...<br>";

$result = mysql_query("UPDATE products a INNER JOIN tmpStock b ON a.products_sku = b.sku SET a.products_quantity = b.quantity")or die ('Error: '.mysql_error ()); echo "All Quantity's Updated...";

mysql_close($link);
4

1 回答 1

0

我很想创建一个临时表,将分隔文件加载到临时表中,然后在现有表和临时表之间使用 JOIN 进行一次更新。

像这样的东西(未经测试,所以请原谅任何错别字)

<?php

$link = mysql_connect('localhost', 'root', '');
If (!$link) 
{
    die ('Could not connect: ' . mysql_error());
}
@mysql_select_db('testarea') or die ('Unable to select database');

echo "Connection succeeded, starting processing..... <br />\n";

$result = mysql_query("CREATE TEMPORARY TABLE tmpStock
(sku varchar(50),
asin varchar(50),
price double(16,2),
quantity int(11),
KEY sku (sku )
) ENGINE=MyISAM DEFAULT CHARSET=latin1 ");

$result = mysql_query("LOAD DATA INFILE 'C:/wamp/www/TestArea/qtyme.txt' INTO TABLE tmpStock FIELDS TERMINATED BY '\t' ENCLOSED BY '\"' LINES TERMINATED BY '\n'")or die ('Error: '.mysql_error ());

$result = mysql_query("UPDATE products a INNER JOIN tmpStock b ON a.products_sku = b.sku SET a.products_quantity = b.quantity")or die ('Error: '.mysql_error ());

?>

PS - 可能应该使用 mysqli,但我坚持使用 mysql,因为那是你已经在使用的。

于 2013-05-13T15:03:16.303 回答