Name | Description |
---|---|
ERRMODE_SILENT | This is the default error mode. PDO sets the error in the database or statement object, but it doesn’t emit a PHP warning message or throw an exception. To access the error, you can use the errorCode() and errorInfo() methods on the database or statement object. However, this requires you to check the error code after each database call. |
ERRMODE_WARNING | PDO sets the error and doesn’t throw an exception as in "silent" mode, but does emit a PHP warning message. This setting is useful during testing and debugging. |
ERRMODE_EXCEPTION | PDO sets the error as in "silent" mode and throws a PDOException object that reflects the error code and error message. This setting is also useful during testing and debugging, and it makes it easier for you to structure your error-handling code. |
$dsn = 'mysql:host=localhost;dbname=my_guitar_shop2'; $username = 'mgs_user'; $password = 'pa55word'; $options = array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION); try { $db = new PDO($dsn, $username, $password, $options); } catch (PDOException $e) { $error_message = $e->getMessage(); echo("Error connecting to database: $error_message<br />"); exit(); }
setAttribute()
method to set the error mode$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
try/catch
statement to catch PDOException objectstry { $query = 'SELECT * FROM product'; $statement = $db->prepare($query); $statement->execute(); $products = $statement->fetchAll(); $statement->closeCursor(); } catch (PDOException $e) { $error_message = $e->getMessage(); echo("Database error: $error_message<br />"); exit(); }