Skip to content

Instantly share code, notes, and snippets.

@terrymun
Created August 18, 2015 22:13
Show Gist options
  • Save terrymun/e87ebabf8ff39699a5dc to your computer and use it in GitHub Desktop.
Save terrymun/e87ebabf8ff39699a5dc to your computer and use it in GitHub Desktop.
Connecting to the MySQL database using PDO, with error catching enabled
<?php
try {
// Open new connection, allow catching of exceptions
$db = new PDO('mysql:host='.DB_HOST.';dbname='.DB_NAME, DB_USER, DB_PASS);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// Wrap the rest of your code in the 'try' block
// since any step in here can go wrong, and you
// will be able to catch any exceptions.
} catch (PDOException $e) {
echo 'PDO exception thrown: '.$e->getMessage();
// Perform error handling
// e.g. Redirect user to a oops-we-messed-up page
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment