PHP PDO Error Handling

PHP PDO Error Handling

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.

PDO Error Modes

There are three main error handling modes in PDO:

  • ERRMODE_SILENT: PDO will set errors silently, and you must manually check for them.
  • ERRMODE_WARNING: PDO will issue a PHP warning but continue execution.
  • ERRMODE_EXCEPTION: PDO will throw a PDOException when an error occurs, making it easier to catch and handle.

Syntax for Setting PDO Error Modes

$dbo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

Example 1: 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();
}
?>

Output:

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

Example 2: ERRMODE_WARNING

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.";
?>

Output:

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.

Example 3: ERRMODE_SILENT

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];
}
?>

Output:

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

PDO Error Handling Functions

PDO::errorCode()

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();
?>

Output:

42S02

PDO::errorInfo()

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);
?>

Output:

Array
(
    [0] => 42S02
    [1] => 1146
    [2] => Table 'testdb.non_existent_table' doesn't exist
)

PDOStatement::errorCode()

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();
?>

Output:

42S02

PDOStatement::errorInfo()

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);
?>

Output:

Array
(
    [0] => 42S02
    [1] => 1146
    [2] => Table 'testdb.non_existent_table' doesn't exist
)

Using try-catch Block in PDO Error Handling

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.

Example: Handling a Wrong SQL Query

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();
}
?>

Output:

Error occurred: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax

Example Code: Logging PDO Errors to a File

Key Points for Logging PDO Errors in PHP
  • Error Handling with try-catch: The try block attempts to execute the PDO operations, while the catch block catches any PDOException errors and processes them.
  • Logging the Error: Use the error_log() function to log errors to a file. The parameter 3 means the message will be appended to the log file.
  • File Permissions: Ensure that the web server has write permissions for the log file location. The file will be created if it doesn't already exist.
  • Customizing Log Path: You can change the log file name or use an absolute path for the log location.
$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.";
}

Example: Handling Errors from Stored Procedures

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();
}
?>

Output:

Stored Procedure Error: SQLSTATE[HY000]: General error: Error executing stored procedure

Best Practices for Using try-catch

  • Use try-catch blocks to ensure that your application doesn’t crash when an error occurs. Instead, you can display user-friendly messages.
  • Always log the detailed error message for debugging, while displaying a generic message to the end-user.
  • For database operations that could potentially fail, wrap the code in a try-catch block to handle errors gracefully.

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.

Error Handling Best Practices

  • Always use ERRMODE_EXCEPTION in development as it makes debugging easier by halting execution and providing detailed error messages.
  • Handle errors gracefully in production environments by catching exceptions and displaying user-friendly messages.
  • Use errorCode() and errorInfo() to get detailed error information when working in ERRMODE_SILENT.

Conclusion

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.


Sample Student table SQL dump SQlite Paging of records

Podcast on MySQL database management using PHP PDO

PDO References
Subscribe to our YouTube Channel here


Subscribe

* indicates required
Subscribe to plus2net

    plus2net.com











    PHP video Tutorials
    We use cookies to improve your browsing experience. . Learn more
    HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
    ©2000-2024 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer