0

I store data into a csv file by this:

$out = fopen('wpo_stock.csv', 'a');
fputcsv($out, array($order_id,$product_id,$product_name,$product_quantity, $regular_price));
fclose($out);

That stores my data in csv perfectly.
The problem is: Every time the page refreshed, it keeps inserting duplicated datas in the csv file.
How can I avoid inserting duplicated data by order_id (order_id is a unique value in my project)?

Code Updated :

$handle = fopen('wpo_stock.csv', 'r');
while (($data = fgetcsv($handle, ",")) !== FALSE) {
if($data[0] != $order_id){
$out = fopen('wpo_stock.csv', 'a');
fputcsv($out, array($order_id,$product_id,$product_name,$product_quantity, $regular_price));
} break;
}
fclose($handle);

1 Answer 1

1

I assume you are trying to override your data all the time when a page refreshes. In that case, you should open your file like this $out = fopen('wpo_stock.csv', 'w');.

But if you are trying to append new data, then you need to read all data from your file and compare with a new one.

Sign up to request clarification or add additional context in comments.

6 Comments

Thanks for answering the [a] is correct because I want append. Exactly, I need to compare new data, but I don't know how to compare csv order_id column with my existing array order_id and if order_id already existing in my csv file don't write them again.
Read all data from your current CSV file and loop it. Inside loop check if any order IDs exists in a new data array.
As you can see in above, I update my code with the way you explain, but now that's not working at all. Am I doing it wrong?
Keep a separate array of "order ids that i've already processed".
IvanIvan ,thanks for answering but, I don't get your point can you explain more and specifically?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.