Skip to content

Magento 2: How to Update Existing Record If Available In the DB Table Or Not then Insert New Row From CSV File

I have tried to import CSV with some following Data, My code is working for insert new record in the table which is in the CSV but not updating the existing record. Everytime when I upload the CSV, it create the new record in Database.

For Example:
Suppose, CSV file contains 2 Columns Username, Price with 3 data rows.

  • Two rows are new which is not available in XYZ table
  • And One Row are already in the XYZ table

So, I want to insert two new rows which is not in the table and update the existing record from the csv data. Also I want to check both column for check existing record in the table.

My Code Sample.

Controller

    <?php

       namespace CustomModuleControllerProduct;

       use CustomModuleModelItemsFactory;

       class Upload extends MagentoFrameworkAppActionAction
       {
        public function __construct(
        Context $context,
        CustomModuleModelItemsFactory  $items,
        ) 
        {
           $this->_items = $items;
        }

            public function execute()
             {
                $err = [];
                $post   =   $this->getRequest()->getPost();
                $filename = $_FILES["prod_massupload"]["tmp_name"];
                $items = $this->_items->create();
                $row = 1;
                 if (($handle = fopen($filename, "r")) !== FALSE) {
                      fgetcsv($handle);
                        while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
    
                                $num = count($data);
                                $row++;
    
                                $items->setData('username',$data[0]);
                                $items->setData('price',$data[1]);
                                $saveData = $items->save(); 
                                $items->unsetData();
                                
                          }
                        fclose($handle);
                        if (!empty($err)) {
                            $errors = implode(',', $err);
                            $this->messageManager->addError($errors);
                        } else {
                            $this->messageManager->addSuccess('Data Imported successfully');
                        }
                    } 
               }

CSV Sample:

enter image description here

Any help will be very appreciated!!