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.
0
0
Error handling with PDO exceptions in PHP
Introduction
When connecting to a database to check if the connection works.
When running a query to make sure it does not fail.
When inserting or updating data to catch mistakes like wrong data types.
When you want to show friendly error messages instead of breaking the whole program.
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
This example connects to the database and runs a query. If anything fails, it shows a message.
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(); } ?>
This example tries to run a wrong SQL command and catches the error to show a message.
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"; } ?>
OutputSuccess
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.