How to do a batch insert in MySQL?

→ Are you a new visitor? Please visit the page guidance for new visitors ←

How to do a batch insert in MySQL?

In this tutorial, I will present you how to do a batch insert in mysql. Let’s say you want to insert some informations from an array into the database. In order for this to work efficient, you should have more than one information in that array.

Why batch insert ?

Because calling insert statements line after line is not the best solution when it comes to performance. You slow down you mysql server and the app will go slow.

How to ?

INSERT statements that use VALUES syntax can insert multiple rows. To do this, include multiple lists of column values, each enclosed within parentheses and separated by commas. Example:

 More practicaly ?

Explain ?

We have a static id called “qId” which should be inserted and a dynamic array containing names that should be inserted with that id also. We construct a for loop in which we parse out “$users” array and we concatenate to our initial sql statement all the names from within that array. Why do we need the if inside ? Because for the first position, we don’t need a comma in front, only for the other ones, starting from the second position.

Result ?

Our query will result into this one:

This is a very fast and productive way to do bulk insert in mysql.

Request an article ←