加载CSV值,然后在mysql数据库中搜索匹配项

时间:2013-09-30 12:24:33

标签: mysql arrays csv match

我正在尝试为cron作业构建一个脚本,从CSV文件中加载一些值。此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);
?>

1 个答案:

答案 0 :(得分:1)

您只在$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
    }
}