PHP
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax
-
Section 3: Functions
-
Section 4: Object-Oriented PHP
-
Section 5: Working with Data
-
Section 6: Modern PHP (PHP 8)
-
Section 7: Working with Files and Networking
-
Section 8: Common PHP Frameworks Overview
-
Section 9: Tooling and Ecosystem
-
Section 10: Practical Projects
-
Section 11: Interview Practice
-
Section 12: More Standard Library
-
Section 13: Data Structures and Algorithms in PHP
-
Section 14: More Practice Exercises
-
Section 15: More Security and Best Practices
-
Section 16: More Testing and Tooling
-
Section 17: WordPress-Style CMS Concepts
-
Section 18: Advanced OOP Practice
-
Section 19: More Web Fundamentals
-
Section 20: Database Practice
-
Section 21: PHP Manual: Array Functions
-
Section 22: PHP Manual: Date and Calendar Functions
-
Section 23: PHP Manual: Filesystem and Directory Functions
-
Section 24: PHP Manual: Filter and Var Handling
-
Section 25: PHP Manual: Math Functions
-
Section 26: PHP Manual: JSON and XML
-
Section 27: PHP Manual: Network and Stream Functions
-
Section 28: PHP Manual: Error and Exception Handling
-
Section 29: PHP Manual: Output Control and Misc
-
Section 30: PHP Manual: FTP, Zip, and Mail
-
Section 31: Modern PHP Frameworks Deep Dive
-
Section 32: PHP Design Patterns
-
Section 33: More Practice Exercises
-
Section 34: PHP Performance and Deployment
-
Section 35: More Interview Practice
-
Section 36: More PHP Standard Library
-
Section 37: PHP Concurrency and Async
-
Section 38: More Web Development Practice
-
Section 39: PHP Testing Deep Dive
-
Section 40: Composer and Package Development
-
Section 41: PHP Security Deep Dive
-
Section 42: More Practical Projects
-
Section 43: Legacy PHP Maintenance
-
Section 44: More Algorithm Practice
-
Section 45: Final Practice and Review
-
Section 46: PHP for E-Commerce Patterns
-
Section 47: PHP API Design Deep Dive
-
Section 48: PHP Caching Strategies
-
Section 49: PHP Queue and Background Jobs
-
Section 50: PHP Multi-Tenancy Patterns
-
Section 51: PHP Real-Time Features
-
Section 52: PHP CMS and Content Modeling
-
Section 53: PHP Internationalization
-
Section 54: More Framework-Specific Practice
-
Section 55: PHP Legacy Code Refactoring
-
Section 56: More Practice Projects Round 2
-
Section 57: PHP Command-Line Applications
-
Section 58: PHP and Microservices
-
Section 59: More Interview and Review Round 2
152: Prepared Statement Batching
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
$priceUpdatescontaining at least 5 associative arrays (each with askuand anew_price). - Write a script that uses a single prepared statement to update the
pricecolumn where theskumatches. - 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.
There are no comments for now.