Prepared statements and why they matter in PHP - Time & Space Complexity
When using prepared statements in PHP, it's important to understand how the time to run your code changes as your data grows.
We want to see how the number of operations changes when preparing and executing statements multiple times.
Analyze the time complexity of the following PHP code using prepared statements.
// Connect to database
$conn = new PDO($dsn, $user, $pass);
// Prepare once
$stmt = $conn->prepare('INSERT INTO users (name, email) VALUES (?, ?)');
// Execute multiple times
foreach ($users as $user) {
$stmt->execute([$user['name'], $user['email']]);
}
This code prepares an SQL insert once, then runs it many times with different data.
Look at what repeats as input grows.
- Primary operation: Executing the prepared statement inside the loop.
- How many times: Once for each user in the input list.
As the number of users grows, the number of execute calls grows the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 execute calls |
| 100 | 100 execute calls |
| 1000 | 1000 execute calls |
Pattern observation: The work grows directly with the number of users; double the users, double the work.
Time Complexity: O(n)
This means the time to run grows in a straight line with the number of inputs.
[X] Wrong: "Preparing the statement inside the loop is just as fast as preparing once."
[OK] Correct: Preparing inside the loop repeats the setup work many times, making the program slower as input grows.
Understanding how prepared statements affect performance shows you can write code that stays fast even with lots of data.
"What if we prepared the statement inside the loop instead of once before? How would the time complexity change?"