Complete the code to catch PDO exceptions.
<?php try { $pdo = new PDO($dsn, $user, $pass); } catch ([1] $e) { echo 'Connection failed: ' . $e->getMessage(); } ?>
The PDOException class is used to catch errors related to PDO database operations.
Complete the code to set PDO to throw exceptions on error.
<?php $pdo = new PDO($dsn, $user, $pass); $pdo->setAttribute(PDO::ATTR_ERRMODE, [1]); ?>
Setting PDO::ATTR_ERRMODE to PDO::ERRMODE_EXCEPTION makes PDO throw exceptions on errors.
Fix the error in the catch block to correctly get the error message.
<?php try { $pdo = new PDO($dsn, $user, $pass); } catch (PDOException $e) { echo 'Error: ' . $e->[1](); } ?>
The getMessage() method returns the error message from the exception.
Fill both blanks to create a try-catch block that connects and sets error mode.
<?php try { $pdo = new PDO([1], $user, $pass); $pdo->setAttribute(PDO::ATTR_ERRMODE, [2]); } catch (PDOException $e) { echo 'Connection failed: ' . $e->getMessage(); } ?>
The variable $dsn holds the data source name string, and setting error mode to PDO::ERRMODE_EXCEPTION enables exception throwing.
Fill all three blanks to create a safe PDO connection with error handling.
<?php try { $pdo = new PDO([1], [2], [3]); $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); } catch (PDOException $e) { echo 'Failed: ' . $e->getMessage(); } ?>
The PDO constructor requires the DSN string, username, and password in that order.