Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have a CSV file with 1 column named EAN and a MySQL Table with a column named EAN too.

This is what I want to do comparing both columns:

CSV ||| MySQL ||| STATUS
123     123       OK
321     321       OK
444               MISSING IN MySQL
        111       MISSING IN CSV

Any ideas how to realize with PHP?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
260 views
Welcome To Ask or Share your Answers For Others

1 Answer

One way to do it:

(Assuming you already know how to open a file and execute a query.)

First read rows from your CSV and assume the data is missing in SQL.

while (($row = fgetcsv($file)) !== FALSE) {
    $num = $row[0];  // or whatever CSV column the value you want is in
    $result[$num] = ['csv' => $num, 'sql' => '', 'status' => 'MISSING IN SQL'];
}

Then fetch rows from your query and fill the array you created from the CSV accordingly.

while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
    $num = $row['EAN']; // or whatever your column is named
    if (isset($result[$num])) {
        // This has a value from the CSV, so update the array
        $result[$num]['sql'] = $num;
        $result[$num]['status'] = 'OK';
    } else {
        // This doesn't have a value from the CSV, so insert a new row
        $result[$num] = ['csv' => '', 'sql' => $num, 'status' => 'MISSING IN CSV'];
    }
}

You could change the order of this and process the query results first. Either order will work, just as long as you do the update/insert logic with the second data source.

You can ksort($result); if you want the merged values to be in order, then output $result however you need to.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...