0

CSV ファイルからいくつかの値をロードする cron ジョブのスクリプトを作成しようとしています。この CSV ファイルには 2 つのフィールドがあります

product_id 
price

スクリプトは CSV から値をロードし、mysql テーブルで product_id の一致を検索します。見つかった場合は、テーブル内の特定の一致した product_id の価格を CSV 内の対応する価格で更新します。

これまでのところ、以下のコードに到達しましたが、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

製品テーブルの最初の行だけを に保存しています$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 に答える