How to use Yii2 Batch Insert?

Yii2 Batch Insert?
Yii2 Batch Insert


How to use Yii2 Batch Insert?

Learn how to insert bulk data with only single query in Yii2 using Batch Insert

We are going to do a batch insert in this tutorial, so what is the batch insert? Well a batch insert is a way that you can enter multiple numbers of records at once to the database.

Suppose we have an excel sheet that has 10,000 rows if we want to import those 10,000 rows in the database using this example.

We will be creating 10,000 model objects and we will be sending 10,000 queries to the database, this is very bad you might know that there is a way that we can have insert multiple number of records to a database with only one query.

Yii2 provides a special function that allow us to do this and makes it really easy so let’s take a look at this function, it’s called the batchInsert()

This batchInsert()  function takes three parameters; the first parameter is the table name, next argument is the number of columns, finally in the third argument we have to add the array of records.

Now let’s create the array of records "$data" in our previous loop.

$data array will look like this:


I am a Sr Android App, Web Developer & Blockchain Project Manager having 5 plus years of extensive hands-on experience in Object Oriented Programming, Database Design and Implementation using Agile & UML. Pro in Yii2 PHP Framework, Android App Development, MYSQL, EOS & Etherium Blockchain & Smart Contract development.

Click to comment

Leave a Reply

Your email address will not be published. Required fields are marked *

More in Yii2

Recent Posts


To Top