Development

Doing MySQL insert from a PHP loop the right way

Effectively manage PHP MySQL inserts from a large loop using the PDO connection.

The key is to avoid committing data on each loop, this is done using a transaction.

Use a transaction

Using beginTransaction and commit means that auto-commit is turned off and the changes made to the database won’t be committed until commit is called.

This method means that on each loop there won’t be an INSERT and re-index of the table, this gets done once at the end on the commit being called.

Be careful with this method because if one loop has an issue the whole INSERT loop will be rolled back and won’t have been a success.

$db = new PDO("mysql:host=127.0.0.1;dbname=test;charset=utf8mb4", 'USER', 'PASS');

$db->beginTransaction();

$insert = $db->prepare('INSERT INTO `objects` (`color`) VALUES (?);');

$test_array = ['Red', 'Orange', 'Pink', 'Lime', 'Yellow', 'Gold', 'Green', 'Blue', 'Purple', 'Maroon', 'Silver', 'Aqua'];

foreach ($test_array as $c) {
    $insert->execute([$c]);
}

$db->commit();

The array used in the example above is very small, with benefits been seen on loops in the several hundreds and above.

A common method that works but is not efficient:

$db = new PDO("mysql:host=127.0.0.1;dbname=test;charset=utf8mb4", 'USER', 'PASS');

$test_array = ['Red', 'Orange', 'Pink', 'Lime', 'Yellow', 'Gold', 'Green', 'Blue', 'Purple', 'Maroon', 'Silver', 'Aqua'];

foreach ($test_array as $c) {
    $insert = $db->prepare('INSERT INTO `objects` (`color`) VALUES (?);');
    $insert->execute([$c]);
}

This will be inserting on every single loop, with checks on indexes and keys each time.

Share

Recent Posts

Kennington reservoir drained drone images

A drained and empty Kennington reservoir images from a drone in early July 2024. The…

1 year ago

Merrimu Reservoir drone images

Merrimu Reservoir from drone. Click images to view larger.

1 year ago

FTP getting array of file details such as size using PHP

Using FTP and PHP to get an array of file details such as size and…

2 years ago

Creating Laravel form requests

Creating and using Laravel form requests to create cleaner code, separation and reusability for your…

2 years ago

Improving the default Laravel login and register views

Improving the default Laravel login and register views in such a simple manner but making…

2 years ago

Laravel validation for checking if value exists in the database

Laravel validation for checking if a field value exists in the database. The validation rule…

2 years ago