PHP PDO Connection
A connection is established by creating an instance of the PDO base class. The PDO class name is used regardless of the driver being used.
Connecting to MySQL
<?php
$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
?>
Note: If there are any connection errors, a PDOException exception object will be thrown.
Handling Connection Errors
<?php
try {
$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
foreach($dbh->query('SELECT * from FOO') as $row) {
print_r($row);
}
$dbh = null;
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
?>
After successfully connecting to the database, 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 by ensuring all remaining references to it are removed, which can be done by assigning a NULL value to the object variable.
If this is not done, PHP will automatically close the connection at the end of the script.
Closing a Connection:
<?php
$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
// Use the connection here
// Now that the script is done, close the connection
$dbh = null;
?>
Many web applications benefit from using persistent connections to database services.
Persistent connections are not closed at the end of the script and are cached. They are reused when another script request is made with the same credentials.
The caching of persistent connections avoids the overhead of establishing a new connection each time a script needs to talk to the database, making web applications faster.
Persistent Connection
<?php
$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass, array(
PDO::ATTR_PERSISTENT => true
));
?>
Note: If you want to use persistent connections, you must set PDO::ATTR_PERSISTENT in the driver options array passed to the PDO constructor. If this attribute is set using PDO::setAttribute() after the object is initialized, the driver will not use persistent connections.