Error handling with PDO exceptions in PHP - Time & Space Complexity
When using PDO exceptions for error handling, it's important to see how the program's steps grow as input changes.
We want to know how the time to handle errors changes when running database queries.
Analyze the time complexity of the following code snippet.
try {
$pdo = new PDO($dsn, $user, $password);
$stmt = $pdo->prepare('SELECT * FROM users WHERE id = ?');
$stmt->execute([$userId]);
$result = $stmt->fetchAll();
} catch (PDOException $e) {
echo 'Error: ' . $e->getMessage();
}
This code tries to run a database query and catches any errors using PDO exceptions.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Fetching all rows with
fetchAll()which loops through the result set. - How many times: Once per row returned by the query, depending on the number of matching users.
As the number of rows returned grows, the time to fetch all results grows too.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 fetch steps |
| 100 | About 100 fetch steps |
| 1000 | About 1000 fetch steps |
Pattern observation: The time grows roughly in direct proportion to the number of rows fetched.
Time Complexity: O(n)
This means the time to fetch results grows linearly with the number of rows returned.
[X] Wrong: "Error handling with exceptions adds a lot of extra time regardless of input size."
[OK] Correct: The exception code runs only when an error happens, so normal queries run in time based on rows fetched, not exception overhead.
Understanding how error handling affects performance helps you write reliable and efficient database code, a useful skill in many projects.
"What if we used fetch() inside a loop instead of fetchAll()? How would the time complexity change?"