Categories: Development

Catching PHP PDO exceptions

How to handle PHP PDO exceptions with the try and catch method to control the flow of any potential errors with PDO connections and queries.

The try and catch exceptions method is a more suited way to get a grasp on problems that coincidently if not handled will throw a fatal error for an uncaught exception bringing your code to a halt.

try {
//Do somehihng
} catch(Exception $e) {
//Error found
}

Now to handle PDO exceptions for a connection function:

function db_connect()
{
    $host = '127.0.0.1';
    $db_name = 'database_name';
    $db_user = 'root';
    $db_password = 'password';
    $db = "mysql:host=$host;dbname=$db_name;charset=utf8mb4";
    $options = array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION);
    try {
        $db_con = new PDO($db, $db_user, $db_password, $options);
        return $db_con;
    } catch (PDOException $e) {
        echo "PDO Error: " . $e->getMessage();
    }
}

When calling this function to create a connection assuming the password/username is incorrect this will be outputted:

PDO Error: SQLSTATE[HY000] [1045] Access denied for user 'root'@'localhost' (using password: NO)

The PDO exception has been caught. If the details were correct then the connection object would be returned.

Now using this try and catch method for a PDO MySQL query:

try {
    $db = db_connect();
    $insert = $db->prepare("INSERT INTO `table` (`col`, `col2`) VALUES (?, ?)");
    $insert->execute([1, 'Gary']);
} catch (PDOException $e) {
    echo "Insert Error: " . $e->getMessage();
}

Once again the exception will be caught and handled properly when the insert query has an error and cannot complete.

 

Share

Recent Posts

Kennington reservoir drained drone images

A drained and empty Kennington reservoir images from a drone in early July 2024. The…

2 years ago

Merrimu Reservoir drone images

Merrimu Reservoir from drone. Click images to view larger.

2 years ago

Early September spring shots

Some early September spring shots from a bushwalk, It is still too early for wildflowers.

3 years ago

Cloning an NVMe to SK Hynix Platinum P41 NVMe

I recently needed to clone over a smaller NVMe to a 2TB SK Hynix Platinum…

3 years ago

Using Laravel’s deleteDirectory to delete folders and their contents

If you ever needed a simple solution in Laravel to delete an entire directory and…

3 years ago

How to allow only 1 user to register in a Laravel application

How to enforce only one user to register or be registered in a Laravel web…

3 years ago