We use error handling with PDO exceptions to catch problems when working with databases. This helps keep the program running smoothly and shows useful messages if something goes wrong.
Error handling with PDO exceptions in PHP
Introduction
Syntax
PHP
<?php try { $pdo = new PDO($dsn, $user, $password); $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // Run database code here } catch (PDOException $e) { echo 'Error: ' . $e->getMessage(); } ?>
The try block contains code that might cause an error.
The catch block runs if an error happens, letting you handle it.
Examples
PHP
<?php try { $pdo = new PDO($dsn, $user, $password); $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $pdo->query('SELECT * FROM users'); } catch (PDOException $e) { echo 'Database error: ' . $e->getMessage(); } ?>
PHP
<?php try { $pdo = new PDO($dsn, $user, $password); $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $pdo->exec('INVALID SQL'); } catch (PDOException $e) { echo 'Query failed: ' . $e->getMessage(); } ?>
Sample Program
This program tries to connect to a database and insert data into a table that does not exist. The error is caught and shown instead of crashing.
PHP
<?php $dsn = 'mysql:host=localhost;dbname=testdb'; $user = 'root'; $password = ''; try { $pdo = new PDO($dsn, $user, $password); $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); echo "Connected successfully\n"; // Intentionally wrong SQL to cause error $pdo->exec('INSERT INTO non_existing_table (name) VALUES ("John")'); } catch (PDOException $e) { echo 'Error: ' . $e->getMessage() . "\n"; } ?>
Important Notes
Always set PDO::ATTR_ERRMODE to PDO::ERRMODE_EXCEPTION to use exceptions.
Use try and catch blocks to handle errors gracefully.
Exceptions give you the error message and code to understand what went wrong.
Summary
PDO exceptions help catch database errors without stopping the program.
Use try and catch to handle errors safely.
Set error mode to exceptions for better error handling.
Practice
1. What is the main purpose of using
try and catch blocks when working with PDO exceptions in PHP?easy
Solution
Step 1: Understand the role of try-catch
Thetryblock runs code that might cause an error, andcatchhandles that error safely.Step 2: Relate to PDO exceptions
PDO exceptions occur on database errors; using try-catch prevents the program from stopping abruptly.Final Answer:
To handle database errors without stopping the entire program -> Option BQuick Check:
try-catch handles errors safely = D [OK]
Hint: Try-catch blocks catch errors to keep programs running [OK]
Common Mistakes:
- Thinking try-catch speeds up queries
- Believing it fixes SQL errors automatically
- Confusing error handling with database creation
2. Which of the following is the correct way to set PDO to throw exceptions on errors?
easy
Solution
Step 1: Identify PDO error modes
PDO supports error modes: SILENT, WARNING, EXCEPTION, and IGNORE (not standard).Step 2: Choose the mode that throws exceptions
PDO::ERRMODE_EXCEPTION makes PDO throw exceptions on errors.Final Answer:
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); -> Option CQuick Check:
Exception mode = PDO::ERRMODE_EXCEPTION = B [OK]
Hint: Use ERRMODE_EXCEPTION to get PDO exceptions [OK]
Common Mistakes:
- Using ERRMODE_SILENT which hides errors
- Confusing ERRMODE_WARNING with exceptions
- Using non-existent ERRMODE_IGNORE
3. What will be the output of this PHP code?
$pdo = new PDO('sqlite::memory:');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
try {
$pdo->exec('CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT)');
$pdo->exec('INSERT INTO users (id, name) VALUES (1, "Alice")');
$pdo->exec('INSERT INTO users (id, name) VALUES (1, "Bob")');
echo "Insert successful";
} catch (PDOException $e) {
echo "Error: " . $e->getMessage();
}medium
Solution
Step 1: Understand the code flow
The code creates a table with a primary key on 'id' and inserts two rows with the same id=1.Step 2: Identify the error
Inserting duplicate primary keys causes an integrity constraint violation, triggering a PDOException.Final Answer:
Error: SQLSTATE[23000]: Integrity constraint violation: UNIQUE constraint failed: users.id -> Option DQuick Check:
Duplicate primary key causes exception = C [OK]
Hint: Duplicate primary keys cause PDOException errors [OK]
Common Mistakes:
- Expecting 'Insert successful' despite duplicate keys
- Thinking it's a syntax error
- Ignoring exception handling output
4. Identify the error in this PHP code snippet that uses PDO exceptions:
try {
$pdo = new PDO('mysql:host=localhost;dbname=testdb', 'user', 'pass');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->exec('INVALID SQL');
} catch (PDOException $e) {
echo 'Error: ' . $e->getMessage();
}medium
Solution
Step 1: Check PDO connection and error mode
The connection string and error mode setting are correct for throwing exceptions.Step 2: Analyze the SQL statement
The SQL statement 'INVALID SQL' is not valid SQL, so it triggers a PDOException.Final Answer:
SQL statement is invalid causing exception -> Option AQuick Check:
Invalid SQL causes exception = A [OK]
Hint: Invalid SQL triggers PDOException if error mode set [OK]
Common Mistakes:
- Assuming connection string is wrong
- Forgetting error mode is set correctly
- Thinking catch block is missing
5. You want to safely insert user data into a database using PDO and handle errors with exceptions. Which of the following code snippets correctly implements this with prepared statements and exception handling?
hard
Solution
Step 1: Check for proper error mode setting
try { $pdo = new PDO($dsn, $user, $pass); $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $stmt = $pdo->prepare('INSERT INTO users (name, email) VALUES (:name, :email)'); $stmt->execute([':name' => $name, ':email' => $email]); echo 'User added'; } catch (PDOException $e) { echo 'Error: ' . $e->getMessage(); } sets PDO::ATTR_ERRMODE to ERRMODE_EXCEPTION, enabling exception handling.Step 2: Verify use of prepared statements and parameter binding
try { $pdo = new PDO($dsn, $user, $pass); $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $stmt = $pdo->prepare('INSERT INTO users (name, email) VALUES (:name, :email)'); $stmt->execute([':name' => $name, ':email' => $email]); echo 'User added'; } catch (PDOException $e) { echo 'Error: ' . $e->getMessage(); } uses prepared statements with named parameters and executes safely with user data.Step 3: Confirm exception handling
try { $pdo = new PDO($dsn, $user, $pass); $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $stmt = $pdo->prepare('INSERT INTO users (name, email) VALUES (:name, :email)'); $stmt->execute([':name' => $name, ':email' => $email]); echo 'User added'; } catch (PDOException $e) { echo 'Error: ' . $e->getMessage(); } catches PDOException and outputs the error message, providing safe error handling.Final Answer:
try { $pdo = new PDO($dsn, $user, $pass); $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $stmt = $pdo->prepare('INSERT INTO users (name, email) VALUES (:name, :email)'); $stmt->execute([':name' => $name, ':email' => $email]); echo 'User added'; } catch (PDOException $e) { echo 'Error: ' . $e->getMessage(); } -> Option AQuick Check:
Prepared + ERRMODE_EXCEPTION + try-catch = A [OK]
Hint: Use prepared statements with ERRMODE_EXCEPTION and try-catch [OK]
Common Mistakes:
- Not setting error mode to exceptions
- Using query() with unescaped variables
- Catching generic Exception instead of PDOException
- Using ERRMODE_WARNING which doesn't throw exceptions
Recommended
Ready to prove it?
Pass the test and this pattern moves unknown
10 questions ~5 mineasy hard
