2

To insert multiple records inside foreach loop we have two options:

example:

foreach($result as $data):

$_model=>Mage::getModel('');
 $_model->setField1()
 $_model->setField2()
 $_model->setField3()
 $_model->setField4()
 $_model->save()
endif;

or

direct SQL query in foreach loop.

Unfortunately both are time consuming process if the loop executes for 10-30 times.

Anyone have any idea as how to make this process faster.

2 Answers 2

12

If they are new rows, you can use the insertMultiple method from the Magento DB Connection class:


$results = array(
    array('field1' => 'value1', 'field2' => 'value2'),
    array('field1' => 'value3', 'field2' => 'value4'),
    array('field1' => 'value5', 'field2' => 'value6')
);
$connection = Mage::getSingleton('core/resource')->getConnection('core_write');
$connection->insertMultiple('your_db_table', $data);

This will be executed in a single query.

5

if we want to go with magento only then below code works great, I used $_model->unsetData(); i don't need to load model in foreach loop.

$_model=>Mage::getModel('');

foreach($result as $data):
 $_model->setField1()
 $_model->setField2()
 $_model->setField3()
 $_model->setField4()
 $_model->save()
 $_model->unsetData();
endif;
1
  • ->unsetData() is what I missed! Commented Aug 6, 2017 at 1:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.