PHP PDO Connection
PHP PDO Reference Manual
A connection is established by creating an instance of the PDO base class. Regardless of which driver is used, the PDO class name is used.
Connecting to MySQL
**Note:** If there are any connection errors, a PDOException object will be thrown.
Handling Connection Errors
query('SELECT * from FOO') as $row) {
print_r($row);
}
$dbh = null;
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "
";
die();
}
?>
After a successful connection, an instance of the PDO class is returned to the script; this connection remains active for the lifetime of the PDO object.
To close the connection, you need to destroy the object to ensure all remaining references to it are deleted; you can assign a NULL value to the object variable.
If you do not do this, PHP will automatically close the connection when the script ends.
Closing a Connection:
Many web applications benefit from using persistent connections to the database service.
Persistent connections are not closed when the script ends; they are cached and reused when another script with the same credentials requests a connection.
Persistent connection caching avoids the overhead of establishing a new connection each time a script needs to talk to the database, making web applications faster.
Persistent Connections
true
));
?>
**Note:** To use a persistent connection, you must set PDO::ATTR_PERSISTENT in the driver options array passed to the PDO constructor. If you set this attribute with PDO::setAttribute() after object initialization, the driver will not use a persistent connection.
PHP PDO Reference Manual