Avoid inserting duplicate data in csv with PHP

22
February 11, 2019, at 3:30 PM

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, 1000, ",")) !== FALSE) {
$mydata = $data[0];
if($mydata != $order_id){
$out = fopen('wpo_stock.csv', 'a');
fputcsv($out, array($order_id,$product_id,$product_name,$product_quantity, $regular_price));
fclose($out); 
}   
    }
    fclose($handle);
Answer 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.

READ ALSO
Why can't I connect to database in xampp? [on hold]

Why can't I connect to database in xampp? [on hold]

I have read all the answers relating to this issue but i couldn't come up with any solutionI have changed config

30
PHP and GEOHASH: how to use GeoHash to calculate distance between 2 points?

PHP and GEOHASH: how to use GeoHash to calculate distance between 2 points?

I understood that GEOHASH allows to hash (lat,long) into a String

48
Edit html table row and update It into mysql table using php

Edit html table row and update It into mysql table using php

I have created update button on my every row in table dynamically using JQuery that successfully editing the table but i don't know how to call php function for updating the database,

11