The connection is established by creating an instance of the PDO base class. Regardless of which driver is used, the PDO class name is used.
<?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.
<?phptry { $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 the data, an instance of the PDO class is returned to the script. This connection remains active during the life cycle of the PDO object.
To close the connection, you need to destroy the object to ensure that all remaining references to it are deleted. You can assign a NULL value to the object variable.
If you don't do this, PHP will automatically close the connection at the end of the script.
<?php$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass); // Use the connection here // Now the run is complete, close the connection here $dbh = null;? >
Many web applications benefit from using persistent connections to database services.
Persistent connections are not closed after the script ends and are cached and reused when another script connection request using the same credentials is made.
Persistent connection caching can make web applications faster by avoiding the overhead of establishing a new connection every time a script needs to talk to the database.
<?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 with PDO::setAttribute() after the object has been initialized, the driver will not use persistent connections.