Skip to content

Instantly share code, notes, and snippets.

@iroegbu
Created November 5, 2014 17:07
Show Gist options
  • Save iroegbu/5baaed6e1c6d79fff1a2 to your computer and use it in GitHub Desktop.
Save iroegbu/5baaed6e1c6d79fff1a2 to your computer and use it in GitHub Desktop.
Proper PDO instantiation
<?php
//for PHP 5.3.6+
try {
$dbh = new PDO('mysql:dbname=databasename;host=hostname;charset=utf8', 'username', 'password');
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
} catch (PDOException $e) {
die("Database connection failed.");
}
//for lower PHP versions
try {
$dbh = new PDO('mysql:dbname=databasename;host=hostname', 'username', 'password');
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$dbh->exec('set names utf8');
} catch (PDOException $e) {
die("Database connection failed.");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment