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

标签 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);
?>

最佳答案

您仅将产品表的第一行存储在$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
    }
}

关于mysql - 加载 CSV 值,然后在 mysql 数据库中搜索匹配项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19094224/

相关文章:

postgresql - 创建从我计算机上的 CSV 文件复制到位于 Postgres 中另一台计算机上的数据库的查询

ruby - 如何删除csv的第一行? ( ruby )

mysql - 如何修复我的sql中的错误代码: 1054.未知列

java - 使用 onItemClickListener 的数组位置

python - 铁蟒 : How to append string to bytearray

php - 按顺序比较PHP中数组的最有效方法?

python - 如何比较两个 pandas 数据帧并删除一个文件上的重复项而不附加其他文件中的数据

php - 使用 latin1_general_ci 将 Unicode 数据插入数据库的最佳方法

sql - 当用户被删除时,我应该如何处理条目?

php - 从一张表中获取ID字段(字段名相同)