PHP do no insert duplicates in database from for loop


I’ve looked through some similar questions but couldnt find a solution. So I am importing data from excel table. Data contains company name, company unique number, city and address.

What I need is, to check if unique number exists in database, and if yes – skip, if no – create record. Below is my code, that is looping through the rows:

for ($i = $data_start_row; $i < $sheetCount + 1; $i++) {
    $externalsales->eik = $spreadSheetAry[$i][$client_eik];
    if ($externalsales->getSocieteByBulstat() > 0) {
    } else {
        $importfromexcel->nom = $spreadSheetAry[$i][$client_name];
        $importfromexcel->address = $spreadSheetAry[$i][$client_address];
        $importfromexcel->town = $spreadSheetAry[$i][$client_city];
        $importfromexcel->tva_intra = $spreadSheetAry[$i][$client_eik];
        $importfromexcel->userId = $user->id;

The problem is, that there are sometimes more than one row in the file, with same data for missing records, so duplicates are created in database. How can I avoid this?

Tried with goto start; where start: is before for loop but this doesnt work (bunch of records for the first missing records are inserted like +500 duplicates).

Setting one of the column as unique is my last option, but I preffer to do it in script.


So, for anyone who stumbles upon here, the final solutions for me is as follows:

Due to some limitations of the database, I was not able to set a unique index for the filed tva_intra in the target table societe so I switched to 2 steps processing

1st step: I have created custom table societe_temp, with same fields as described in the question, and for this table I was able to set a unique index for field tva_intra:

`ALTER TABLE societe_temp ADD UNIQUE idx_societe_temp_tva_intra (tva_intra);`

Then insert the records from the excel file in this table thus avoiding any duplicate records.

2nd step Get the records from the temp table societe_temp and insert them in the master table ‘societe’

I know this is not the most optimal solution, but it is a workaround that can help someone someday.

Answered By – milenmk

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published