Csv find duplicate entries

Hy, I’ have problem with csv, I want to find duplicate entries before i enter data in database. But i want to check only for first column in code that’s it $data[0]
Here’s the code:

$konekcija_amso = pg_connect("dbname=mojabaza user=userja host=localhost" );
if(isset($_POST['enter'])) 
{
       $fajl = $_FILES['file']['tmp_name'];
    if((($handle = fopen($fajl, 'r')) !== false))
        {
            while(($data = fgetcsv($handle,1000, ',')) !== false)
            {

/*
before entries data i want $data[0] to check is there duplicate values, if has show message and stop entries in table csvtrenutna

            */
            
            $sql = "INSERT INTO csvtrenutna (brpolise, iznos) VALUES('".$data[0]."', '".$data[1]."')";
            pg_query($konekcija, $sql);
            
         
        }
        
    }
    fclose($handle);
}

<form action="" method="post" enctype="multipart/form-data" id="formarasknjizavanje">
        <input type="file" name="file" id = "file" >
   
        <input type="button" name="enter" value="Rasknjizi">
    </form>

The simpliest way to do that is use an array to store already added values and check for duplicates.

if((($handle = fopen($fajl, 'r')) !== false)) {
    $stored = [];
    while(($data = fgetcsv($handle,1000, ',')) !== false) {

        //skip current row if it is a duplicate
        if (in_array($data[0], $stored)) { continue;}

        $sql = "INSERT INTO csvtrenutna (brpolise, iznos) VALUES('".$data[0]."', '".$data[1]."')";
        pg_query($konekcija, $sql);

        //remember inserted value
        $stored[] = $data[0];

    }
}

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.