0
0
PHPprogramming~30 mins

Error handling with PDO exceptions in PHP - Mini Project: Build & Apply

Choose your learning style9 modes available
Error handling with PDO exceptions
📖 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
Need a 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
Need a 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
Need a 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
Need a hint?

Use foreach ($users as $user) to print names and echo "Error: " . $e->getMessage(); in catch.