Preventing injection with prepared statements in PHP - Time & Space Complexity
We want to understand how the time needed to run prepared statements changes as we handle more data.
How does the program's work grow when using prepared statements to prevent injection?
Analyze the time complexity of the following code snippet.
// Prepare the SQL once
$stmt = $pdo->prepare('SELECT * FROM users WHERE email = ?');
// Loop through emails to execute the statement
foreach ($emails as $email) {
$stmt->execute([$email]);
$result = $stmt->fetchAll();
}
This code prepares a query once and runs it multiple times with different emails to safely get user data.
- Primary operation: Executing the prepared statement and fetching results inside the loop.
- How many times: Once for each email in the input list.
Each new email means one more execution and fetch operation.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 executions and fetches |
| 100 | About 100 executions and fetches |
| 1000 | About 1000 executions and fetches |
Pattern observation: The work grows directly with the number of emails; doubling emails doubles the work.
Time Complexity: O(n)
This means the time needed grows in a straight line as the number of emails increases.
[X] Wrong: "Preparing the statement inside the loop is just as fast as preparing it once."
[OK] Correct: Preparing inside the loop repeats setup work each time, making the program slower as input grows.
Understanding how prepared statements scale helps you write safe and efficient code, a skill valued in real projects and interviews.
"What if we prepared the statement inside the loop instead of once before it? How would the time complexity change?"