Binding parameters in PHP - Time & Space Complexity
When using binding parameters in PHP, it's important to see how the time to prepare and execute queries changes as input grows.
We want to know how the number of operations grows when binding many parameters.
Analyze the time complexity of the following code snippet.
$stmt = $pdo->prepare('INSERT INTO users (name, age) VALUES (?, ?)');
foreach ($users as $user) {
$stmt->bindParam(1, $user['name']);
$stmt->bindParam(2, $user['age']);
$stmt->execute();
}
This code prepares a query once, then binds parameters and executes it for each user in the list.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping over each user to bind parameters and execute the query.
- How many times: Once for each user in the input array.
As the number of users grows, the number of bind and execute operations grows the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 binds and 10 executes |
| 100 | About 100 binds and 100 executes |
| 1000 | About 1000 binds and 1000 executes |
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 bind and execute grows in a straight line as the number of users increases.
[X] Wrong: "Binding parameters once before the loop makes the whole process constant time."
[OK] Correct: Each user needs its own bind and execute call, so the work still grows with the number of users.
Understanding how binding parameters scales helps you write efficient database code and explain your reasoning clearly in interviews.
"What if we prepared and executed the query inside the loop instead of once before? How would the time complexity change?"