PHP Data Objects (PDO) is a robust and consistent way to interact with databases in PHP. Error handling is an important aspect of using PDO as it allows developers to catch and manage errors efficiently. In this post, we’ll explore the different error handling modes provided by PDO and how to use various functions to gather error-related information.
There are three main error handling modes in PDO:
$dbo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
In this mode, the PDO will throw an exception when it encounters an error.
<?php
try {
$dbo = new PDO("mysql:host=localhost;dbname=testdb", "username", "password");
$dbo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// Deliberate SQL syntax error
$sql = "SELCT * FROM student";
$dbo->query($sql);
} catch (PDOException $e) {
echo "Error: " . $e->getMessage();
}
?>
Error: SQLSTATE[42000]: Syntax error or access violation: 1064
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'SELCT * FROM student' at line 1
This mode will generate a PHP warning but continue execution.
<?php
$dbo = new PDO("mysql:host=localhost;dbname=testdb", "username", "password");
$dbo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
// SQL syntax error
$sql = "SELCT * FROM student";
$dbo->query($sql);
echo "Execution continues despite the warning.";
?>
Warning: PDO::query(): SQLSTATE[42000]: Syntax error or access violation: 1064
You have an error in your SQL syntax; check the manual that corresponds to your M
ySQL server version for the right syntax to use near 'SELCT * FROM student' at line 1 in<file>
Execution continues despite the warning.
In this mode, PDO will not raise any warning or exception. You must check for errors manually.
<?php
$dbo = new PDO("mysql:host=localhost;dbname=testdb", "username", "password");
$dbo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_SILENT);
// SQL syntax error
$sql = "SELCT * FROM student";
$result = $dbo->query($sql);
if (!$result) {
$errorInfo = $dbo->errorInfo();
echo "Error Code: " . $errorInfo[0];
echo "<br>Error Info: " . $errorInfo[2];
}
?>
Error Code: 42000
Error Info: You have an error in your SQL syntax; check the manual that corresponds to your
MySQL server version for the right syntax to use near 'SELCT * FROM student' at line 1
This method retrieves the SQLSTATE code associated with the last operation on the database handle. It returns a five-character SQLSTATE code, or NULL if no operation has been executed yet.
<?php
$dbo = new PDO("mysql:host=localhost;dbname=testdb", "username", "password");
$sql = "SELECT * FROM non_existent_table";
$dbo->query($sql);
echo $dbo->errorCode();
?>
42S02
This method returns an array with three elements containing error information about the last operation on the database handle.
<?php
$dbo = new PDO("mysql:host=localhost;dbname=testdb", "username", "password");
$sql = "SELECT * FROM non_existent_table";
$dbo->query($sql);
$errorInfo = $dbo->errorInfo();
print_r($errorInfo);
?>
Array
(
[0] => 42S02
[1] => 1146
[2] => Table 'testdb.non_existent_table' doesn't exist
)
This method works similarly to PDO::errorCode() but is used on the statement handle instead of the database handle.
<?php
$dbo = new PDO("mysql:host=localhost;dbname=testdb", "username", "password");
$stmt = $dbo->prepare("SELECT * FROM non_existent_table");
$stmt->execute();
echo $stmt->errorCode();
?>
42S02
This method is similar to PDO::errorInfo() but is called on a statement handle. It returns an array with information related to the last statement operation.
<?php
$dbo = new PDO("mysql:host=localhost;dbname=testdb", "username", "password");
$stmt = $dbo->prepare("SELECT * FROM non_existent_table");
$stmt->execute();
$errorInfo = $stmt->errorInfo();
print_r($errorInfo);
?>
Array
(
[0] => 42S02
[1] => 1146
[2] => Table 'testdb.non_existent_table' doesn't exist
)
The try-catch block is a powerful way to handle errors in PHP, especially when working with PDO. When PDO is set to ERRMODE_EXCEPTION, any error that occurs can be caught in a PDOException. This allows for more graceful error handling and helps you manage errors in a more controlled way.
In this example, we will try to execute a query with an SQL syntax error and handle it using a try-catch block.
<?php
try {
$dbo = new PDO("mysql:host=localhost;dbname=testdb", "username", "password");
$dbo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// Wrong SQL syntax (deliberate mistake in the SQL keyword)
$sql = "SELCT * FROM student";
$dbo->query($sql);
} catch (PDOException $e) {
// Handle the error
echo "Error occurred: " . $e->getMessage();
}
?>
Error occurred: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax
try-catch
: The try
block attempts to execute the PDO operations, while the catch
block catches any PDOException
errors and processes them.error_log()
function to log errors to a file. The parameter 3
means the message will be appended to the log file.$dsn = 'mysql:host=localhost;dbname=testdb';
$username = 'root';
$password = '';
try {
// Create a PDO instance
$pdo = new PDO($dsn, $username, $password);
// Set the PDO error mode to Exception
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// Example query
$sql = "SELECT * FROM non_existent_table"; // This will cause an error
// Execute the query
$stmt = $pdo->query($sql);
} catch (PDOException $e) {
// Log the error to a file
error_log("PDO Error: " . $e->getMessage(), 3, "pdo_errors.log");
// Optionally display a user-friendly message (optional for production)
echo "There was a problem with the database connection. Please try again later.";
}
Stored procedures can also generate errors when executed through PDO. In the example below, we demonstrate how to handle an error caused by a stored procedure using a try-catch block.
<?php
try {
$dbo = new PDO("mysql:host=localhost;dbname=testdb", "username", "password");
$dbo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// Assuming the stored procedure `sp_get_users` exists but has an issue
$sql = "CALL sp_get_users()";
$dbo->exec($sql);
} catch (PDOException $e) {
// Handle the stored procedure error
echo "Stored Procedure Error: " . $e->getMessage();
}
?>
Stored Procedure Error: SQLSTATE[HY000]: General error: Error executing stored procedure
By using try-catch blocks, you can handle PDO errors more effectively, whether it's an SQL syntax error or an issue with a stored procedure. This method ensures that errors are managed in a controlled way, preventing your application from crashing unexpectedly.
PDO provides several powerful ways to handle errors through different error modes and functions like errorCode() and errorInfo(). By choosing the right error mode and handling errors correctly, you can make your PHP applications more reliable and easier to debug.