Magento, Magento 2

How to Insert Multiple Records into Database Table in Magento 2

How to Insert Multiple Records into Database Table in Magento 2

In this tutorial, Today I will explain to how to insert multiple records into database table in Magento 2. Generally, Using Model or Factory we add single records into database table. However, sometimes we require to insert multiple rows into database table.

If you create factory model class and call into foreach loop to insert multiple records then it maybe slow down performance. But, using this way you can insert multiple rows into database table and also increase performance. Because, this way is more better than factory with foreach loop. So, Let’s start step by step to implement this code.

You may also like this :

Steps to Insert Multiple Records into Database Table in Magento 2 :

1) First of all, Let’s assume that you have created simple module in Magento 2. After that, You can use this below code into Index.php Controller file at app/code/RH/Helloworld/Controller/Index and paste the below code :

<?php
/**
 * Created By : Rohan Hapani
 */
namespace RH\Helloworld\Controller\Index;

class Index extends \Magento\Framework\App\Action\Action
{

    /**
     * @var \Magento\Framework\View\Result\PageFactory
     */
    protected $resultPageFactory;

    /**
     * @var \Magento\Framework\App\ResourceConnection
     */
    protected $resource;

    protected $connection;

    /**
     * @param \Magento\Framework\App\Action\Context $context
     * @param \Magento\Framework\View\Result\PageFactory resultPageFactory
     * @param \Magento\Framework\App\ResourceConnection $resource
     */
    public function __construct(
        \Magento\Framework\App\Action\Context $context,
        \Magento\Framework\View\Result\PageFactory $resultPageFactory,
        \Magento\Framework\App\ResourceConnection $resource
    ) {
        $this->resultPageFactory = $resultPageFactory;
        $this->resource = $resource;
        $this->connection = $resource->getConnection();
        parent::__construct($context);
    }
    
    public function execute()
    {
        $resultPage = $this->resultPageFactory->create();
        // Code for insert multiple data
        try {
            $rhCustomArray = [
                ['id' => 1, 'code' => 'in', 'label' => 'India']
                ['id' => 2, 'code' => 'de', 'label' => 'Germany'],
                ['id' => 3, 'code' => 'us', 'label' => 'United States'],
            ];
            $tableName = 'rh_helloworld_table'; // Add here your module's table name
            $this->insertMultiple($tableName, $rhCustomArray);
            $this->messageManager->addSuccess( __('Multiple data inserted successfully.') );
        } catch (\Exception $e) {
            $this->messageManager->addException($e, __('Something went wrong while saving the data.'));
        }
        $resultPage->getConfig()->getTitle()->prepend(__('Welcome to RH Helloworld module'));
        return $resultPage;
    }

    public function insertMultiple($table, $data)
    {
        try {
            $tableName = $this->resource->getTableName($table);
            return $this->connection->insertMultiple($tableName, $data);
        } catch (\Exception $e) {
            $this->messageManager->addException($e, __('Something went wrong while saving the data.'));
        }
    }
}

2) Now, Just execute this below commands for that :

When you execute this controller then data will be save successfully. The main advantage of this way is it’s too much faster than factory with foreach loop code. It will be helpful to improve website speed performance.

That’s it !!!

I hope this blog is easy to understand about how to insert multiple records into database table in Magento 2. In case, I missed anything or need to add some information, always feel free to leave a comment in this blog, I’ll get back with proper solution.

Keep liking and sharing !!

Tagged ,