我正在尝试为 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/