This short post is about adding a lot of rows to a MySQL database from a simple PHP script. You will not find server tuning here, nor tools like Doctrine. What you will find is measurements: the same 100,000 rows inserted in nine different ways, from 700 to over 100,000 rows a second.
In short
- The biggest brake is committing every row separately. One transaction for the whole import is over 30 times faster.
- Batch your rows: one INSERT with 1,000 rows is over 100 times faster than 1,000 single ones in autocommit mode.
- Dropping indexes for the import did not help in my tests, not even with a million rows.
How I measured
Picture a PHP script that imports data from a CSV file into a database (so that it can be parsed, validated or mined a little first). The test table is a typical "orders" table: a primary key, an email (unique), a name, a city, an amount and a date, with indexes on the email, the city and the date. InnoDB engine, utf8mb4 encoding.
Setup: MySQL 5.7.44 (a version still common on shared hosting) in Docker on an ordinary laptop, PHP 8 with mysqli, default server settings. Your server will give different numbers, but the proportions between methods should be similar.
"But you can just import a CSV in phpMyAdmin..." True 😉 Not everyone has access to it, though, and it is hard to automate - and loading the data is often just the first step of a longer script. Besides, the file may be irregular: say, the first column is a key and the rest are its values, which go into the database as separate rows or as JSON.
Results
100,000 rows, the same indexed table, starting from scratch each time:
- 1 row per query, autocommit - 700 rows/s (measured on 5,000 rows; the whole lot would take about 2.5 minutes)
- 10 rows per query, autocommit - 5,784 rows/s (17.3 s)
- 1 row per query, one transaction - 22,639 rows/s (4.4 s)
- prepared statement, one transaction - 26,110 rows/s (3.8 s)
- 100 rows per query, autocommit - 41,286 rows/s (2.4 s)
- LOAD DATA LOCAL INFILE from a CSV - 71,773 rows/s (1.4 s)
- 1,000 rows per query, autocommit - 86,442 rows/s (1.2 s)
- 5,000 rows per query, autocommit - 101,982 rows/s (1.0 s)
And a separate test with a million rows, 1,000 per query:
- with indexes, autocommit - 71,014 rows/s (14.1 s)
- with indexes, one transaction - 95,042 rows/s (10.5 s)
- no indexes, added at the end - 66,235 rows/s (15.1 s)
Transactions: do not commit every row
The most striking difference is between the first and the third result: the same row-by-row inserts, over 30 times faster. Why? In autocommit mode every INSERT is a transaction of its own, and with default settings MySQL waits after each commit until the write has physically reached the disk. With 100,000 rows, that is 100,000 waits.
$db->begin_transaction();
foreach ($rows as $row) {
// INSERT ...
}
$db->commit();
You can see it in the 10-rows-per-query result too: batching helped, but single rows in one transaction were still four times faster. A bonus: if something goes wrong halfway through, rollback() undoes the lot and you are not left with half the data in the database.
Batching values
The second brake is the number of queries. Each is a round trip to the server, plus parsing and planning. One INSERT with many rows does that once:
INSERT INTO orders (email, name, city, amount, created) VALUES
('[email protected]', 'Anna', 'Leeds', 120.50, '2026-12-01 10:00:00'),
('[email protected]', 'John', 'Bristol', 89.99, '2026-12-01 10:05:00'),
...
From 10 to 1,000 rows per query the gain is huge; after that it is small (5,000 gave only 18% more than 1,000). The limit is the size of one query: the max_allowed_packet variable, 4 MB on my MySQL. With short rows, 1,000 is about 100 KB, but with long texts it is easy to go over and get "MySQL server has gone away". It is safer to size a batch in bytes than in rows.
A ready script
It combines both lessons: batches of 1,000 rows and one transaction.
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$db = new mysqli('localhost', 'user', 'password', 'database');
$db->set_charset('utf8mb4');
$sql = 'INSERT INTO orders (email, name, city, amount, created) VALUES ';
$batch = [];
$file = fopen('orders.csv', 'r');
$db->begin_transaction();
while (($row = fgetcsv($file)) !== false) {
$batch[] = sprintf(
"('%s','%s','%s',%.2F,'%s')",
$db->real_escape_string($row[0]),
$db->real_escape_string($row[1]),
$db->real_escape_string($row[2]),
(float) $row[3],
$db->real_escape_string($row[4])
);
if (count($batch) === 1000) {
$db->query($sql . implode(',', $batch));
$batch = [];
}
}
if ($batch) {
$db->query($sql . implode(',', $batch));
}
$db->commit();
real_escape_string is not optional here: without it, an apostrophe in a surname (O'Brien) breaks the import, and a maliciously prepared file could inject SQL of its own. If you prefer prepared statements, that works too: build one query with 1,000 groups of question marks and execute it repeatedly.
LOAD DATA: let MySQL read the file
LOAD DATA LOCAL INFILE loads a CSV file in one statement and was fast (72,000 rows/s), though slightly slower than big INSERT batches in this test. It has two catches: the file has to be in its final format already (no validation on the way), and the local_infile option is often switched off on shared hosting for security reasons. A good choice when you control the server and the file is clean.
Indexes: drop them or not?
The popular advice is: drop indexes before an import and add them afterwards. In my tests it did not help, neither with 100,000 nor with a million rows - building the indexes at the end took longer than the import saved. As long as the indexes fit in the server's memory (the InnoDB buffer pool), updating them as you go is cheap.
The advice starts to make sense at tens of millions of rows, once the indexes no longer fit in memory. Then it is worth measuring on your own data - and remember that a unique index cannot be skipped safely: duplicates only show up when you add it back.
What else you could check
A few things from my list I did not measure, because their effect depends heavily on the server and the data: ROW_FORMAT (DYNAMIC, COMPRESSED), the character set and collation, partitions, and server settings such as innodb_flush_log_at_trx_commit or the InnoDB buffer size. The last ones can make a big difference, but on shared hosting you usually cannot touch them. To experiment yourself, you can set up MySQL in Docker in minutes (an example is in A local Apache server in Docker). And how indexes speed up searching is explained in What is a database index?