Connections are established by creating instances of the PDO base class. It doesn't matter which driver you want to use; you always use the PDO class name. The constructor accepts parameters for specifying the database source (known as the DSN) and optionally for the username and password (if any).
Example #1 Connecting to MySQL
<?php
$dbh = new PDO('mysql:host=localhost;dbname=pcdsdb', $user, $pass);
?>
If there are any connection errors, a PDOException object will be thrown. You may catch the exception if you want to handle the error condition, or you may opt to leave it for an application global exception handler that you set up via set_exception_handler().
Example #2 Handling connection errors
<?php
try {
$dbh = new PDO('mysql:host=localhost;dbname=pcdsdb', $user, $pass);
foreach($dbh->query('SELECT * from tableemp') as $row) {
print_r($row);
}
$dbh = null;
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
?>
Example #4 Persistent connections
<?php
$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass, array(
PDO::ATTR_PERSISTENT => true
));
?>