📖 Scenario: You are building a simple PHP script to connect to a database and fetch user data. Sometimes, the connection or query might fail. To handle these problems safely, you will use PDO exceptions.
🎯 Goal: Create a PHP script that connects to a database using PDO, runs a query to get user names, and handles any errors using PDO exceptions.
📋 What You'll Learn
Create a PDO connection to a MySQL database with given credentials.
Set the PDO error mode to throw exceptions.
Write a try-catch block to catch PDO exceptions.
Run a simple SELECT query to get user names from a table called users.
Print the user names if the query succeeds.
Print an error message if an exception occurs.
💡 Why This Matters
🌍 Real World
Handling database errors gracefully is important in real web applications to avoid crashes and show friendly messages.
💼 Career
Knowing how to use PDO exceptions is a key skill for PHP developers working with databases securely and reliably.
Progress0 / 4 steps
1
Create a PDO connection
Create a new PDO object called $pdo to connect to a MySQL database with these exact details: host localhost, database name testdb, username root, and password password123.
PHP
Hint
Use new PDO() with the DSN string and credentials exactly as given.
2
Set PDO error mode to exceptions
Set the PDO attribute PDO::ATTR_ERRMODE on $pdo to PDO::ERRMODE_EXCEPTION using the setAttribute method.
PHP
Hint
Use $pdo->setAttribute() to set the error mode.
3
Write try-catch block with query
Write a try block where you run the query SELECT name FROM users using $pdo->query() and fetch all results with fetchAll(PDO::FETCH_ASSOC) into a variable called $users. Then write a catch block to catch PDOException as $e.
PHP
Hint
Use try { ... } catch (PDOException $e) { ... } and run the query inside the try block.
4
Print results or error message
Inside the try block, use a foreach loop with variables $user to print each user name with echo $user['name'] . "\n";. Inside the catch block, print the error message with echo "Error: " . $e->getMessage();.
PHP
Hint
Use foreach ($users as $user) to print names and echo "Error: " . $e->getMessage(); in catch.
Practice
(1/5)
1. What is the main purpose of using try and catch blocks when working with PDO exceptions in PHP?
easy
A. To create new database tables
B. To handle database errors without stopping the entire program
C. To automatically fix SQL syntax errors
D. To speed up database queries
Solution
Step 1: Understand the role of try-catch
The try block runs code that might cause an error, and catch handles 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 B
Quick 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
A. $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_SILENT);
B. $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
C. $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
D. $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_IGNORE);
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 A
Quick 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?