Skip to Content
Course content

152: Prepared Statement Batching

Click on the "Edit" button in the top corner of the screen to edit your slide content.

Why can't I just put the prepare() call inside my loop?

I see this all the time when developers are first handling bulk imports. They'll write a loop to iterate through a CSV file and put both the prepare() and the execute() calls inside that loop. Technically, it works, but you're killing your performance.

Think of prepare() as telling the database: "Hey, I'm about to send you a specific pattern of data; go ahead and figure out the most efficient way to execute this query." If you put that inside a loop of 1,000 items, you're asking the database to "plan" the same query 1,000 times. That's a waste of CPU cycles on the DB server. You only need to prepare the statement once, and then you just "pump" the data through it using execute().

How do I actually send different values to the same statement?

It's simpler than it sounds. You prepare the SQL with your placeholders, and then you call execute() inside the loop, passing in a different array of values each time. The database keeps the "plan" in memory and just swaps the values.

Let's say we're importing a batch of new products from a supplier's list. Here is how I'd structure that:

$products = [
    ['name' => 'Mechanical Keyboard', 'sku' => 'KB-123', 'price' => 89.99],
    ['name' => 'Gaming Mouse', 'sku' => 'MS-456', 'price' => 45.00],
    ['name' => 'UltraWide Monitor', 'sku' => 'MN-789', 'price' => 320.50],
    // Imagine hundreds more rows here...
];

// 1. Prepare ONCE outside the loop
$stmt = $pdo->prepare("INSERT INTO products (product_name, sku, price) VALUES (:name, :sku, :price)");

foreach ($products as $product) {
    // 2. Execute MANY times with different data
    $stmt->execute([
        ':name'  => $product['name'],
        ':sku'   => $product['sku'],
        ':price' => $product['price']
    ]);
}

I personally prefer named placeholders (like :name) over positional ones (?) for batching. When your tables get wider—say, 20 columns—trying to remember if the "discount_rate" was the 14th or 15th question mark becomes a nightmare.

Will this actually be faster if I'm doing thousands of rows?

Moving prepare() outside the loop is a great start, but if you're dealing with thousands of rows, you'll hit another bottleneck: the disk. By default, most databases wrap every single INSERT in its own implicit transaction. This means the database has to ensure the data is physically written to the disk before it moves to the next row. That's a lot of slow I/O.

To really make this fly, wrap the whole loop in a single transaction. This tells the database to hold all the changes in memory and commit them to the disk in one single burst at the end.

$pdo->beginTransaction();

try {
    $stmt = $pdo->prepare("INSERT INTO products (product_name, sku, price) VALUES (:name, :sku, :price)");
    
    foreach ($products as $product) {
        $stmt->execute($product);
    }
    
    $pdo->commit(); 
} catch (Exception $e) {
    $pdo->rollBack();
    throw $e;
}

In my experience, combining a single prepared statement with a transaction can turn a 30-second import into a sub-second operation. It's a massive difference.




📋 Practical Task

Exercise: Building a Bulk Product Price Updater

You've been given an array of product SKUs and their new updated prices. Your task is to update the products table in the database efficiently.

  • Create an array called $priceUpdates containing at least 5 associative arrays (each with a sku and a new_price).
  • Write a script that uses a single prepared statement to update the price column where the sku matches.
  • Wrap the entire execution loop in a transaction to ensure that either all prices are updated or none are (atomicity).
  • Ensure the prepare() call happens outside the loop.
Rating
0 0

There are no comments for now.

to be the first to leave a comment.