0
0
PHPprogramming~5 mins

How SQL injection exploits unsafe queries in PHP - Performance & Efficiency

Choose your learning style9 modes available
Time Complexity: How SQL injection exploits unsafe queries
O(n)
Understanding Time Complexity

We want to see how the time to run a PHP query changes when it is unsafe and vulnerable to SQL injection.

How does the way we build queries affect how long they take to run?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


$user_input = $_GET['id'];
$query = "SELECT * FROM users WHERE id = " . $user_input;
$result = mysqli_query($conn, $query);
while ($row = mysqli_fetch_assoc($result)) {
    echo $row['name'];
}
    

This code builds a SQL query by directly adding user input, then fetches and prints matching user names.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Looping through query results with mysqli_fetch_assoc.
  • How many times: Once for each matching row in the database.
How Execution Grows With Input

The number of rows returned depends on the query built from user input. Unsafe input can cause many rows to be returned.

Input Size (n)Approx. Operations
1 (safe id)1 row fetched, few operations
10 (malicious input returns 10 rows)10 rows fetched, 10 times loop
1000 (malicious input returns 1000 rows)1000 rows fetched, 1000 times loop

Pattern observation: More rows returned means more loop iterations, so execution grows with result size.

Final Time Complexity

Time Complexity: O(n)

This means the time grows linearly with the number of rows returned by the query.

Common Mistake

[X] Wrong: "The query time depends only on the input size, not on how the query is built."

[OK] Correct: Unsafe queries can return many more rows than expected, making the loop run longer and increasing execution time.

Interview Connect

Understanding how unsafe queries affect execution time helps you write safer code and explain why security matters in real projects.

Self-Check

"What if we used prepared statements instead of direct string building? How would the time complexity change?"