0
0
PHPprogramming~5 mins

Preventing injection with prepared statements in PHP - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Preventing injection with prepared statements
O(n)
Understanding Time 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?

Scenario Under Consideration

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.

Identify Repeating Operations
  • Primary operation: Executing the prepared statement and fetching results inside the loop.
  • How many times: Once for each email in the input list.
How Execution Grows With Input

Each new email means one more execution and fetch operation.

Input Size (n)Approx. Operations
10About 10 executions and fetches
100About 100 executions and fetches
1000About 1000 executions and fetches

Pattern observation: The work grows directly with the number of emails; doubling emails doubles the work.

Final Time Complexity

Time Complexity: O(n)

This means the time needed grows in a straight line as the number of emails increases.

Common Mistake

[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.

Interview Connect

Understanding how prepared statements scale helps you write safe and efficient code, a skill valued in real projects and interviews.

Self-Check

"What if we prepared the statement inside the loop instead of once before it? How would the time complexity change?"