0

我正在尝试为从 CSV 文件加载一些值的 cron 作业构建一个脚本。此 CSV 文件有 2 个字段

product_id 
price

该脚本将从 CSV 加载值,然后在 mysql 表中搜索 product_id 匹配项。如果找到,它将使用 CSV 中的相应价格更新表中该特定匹配 product_id 的价格。

到目前为止,我到达了下面的代码,但我陷入了需要将 CSV 中的数组值与 mysql 中的数组值进行比较的部分。

<?php
// DB part
$con = mysqli_connect('localhost','user','pass','db');
if (!$con)
  {
  die('Could not connect: ' . mysqli_error($con));
  }

mysqli_select_db($con,"products");

        $sql="SELECT product_id, price, FROM products";

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

// CSV part
$file_handle = fopen("prices.csv", "r");


while (!feof($file_handle) ) {

    $line_of_text = fgetcsv($file_handle, 1024);

    $code = str_replace(' ', '', $line_of_text[0]); // 
    $price = str_replace(' ', '', $line_of_text[1]); // 



     if (in_array($code, str_replace(' ', '', $row)))
          {
          echo "Match found";
          print $code . " - " . $price . "<br />";
          }
            else
          {
          echo "Match not found";
          print $code . " - " . $price . "<br />";
          }
    }
fclose($file_handle);
mysqli_close($con);
?>
4

1 回答 1

1

您仅将products表的第一行存储在$row. 然后你做了一些难以理解的比较,但所有这些比较都只比较你的第一行。

这是我要做的:

// Untested Code Below, Not Suited For Production Use

// ...
// open the DB connection, open the file, etc.
// ...

// iterate over the complete CSV file
while (!feof($file_handle) ) {
    $line_of_text = fgetcsv($file_handle, 1024);
    $product_id = clean_product_id($line_of_text[0]);
    $price = $line_of_text[1];
    // for any entry in the CSV file check if there is more than one result
    $sql="SELECT COUNT(*) FROM products WHERE product_id='$product_id'";
    $result = mysqli_query($con,$sql);
    $row = mysqli_fetch_array($result);
    if( $row[0] == 1 ) {
        // update the table price for the corresponding row (product), if there is just a single result for this $product_id
        $sql="UPDATE products SET price = '$price' WHERE product_id='$product_id' LIMIT 1"; // in production code use mysqli_real_escape_string() on $price and $product_id!
        $result = mysqli_query($con,$sql);
    } else {
        // if there are more results for this $product_id, add an error to your report.txt file
    }
}
于 2013-09-30T13:29:50.080 回答