Latest web development tutorials

PHP PDO connection manager

PHP PDO Reference Manual PHP PDO Reference Manual

Connection is by creating an instance of the PDO base class established. Regardless of the driver, are used PDO class name.

Connect to MySQL

<?php
$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
?>

Note: If there are any connection errors, will throw an exception object PDOException.

Handle 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 a successful connection data, return an instance of the PDO class to the script, in this connection lifetime PDO object remains active.

To close the connection, you need to destroy the object in order to ensure that all remaining references to it are deleted, you can assign a NULL value to the object variable.

If you do not do that, PHP at the end of the script will automatically close the connection.

To close a connection:

<?php
$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
// 在此使用连接


// 现在运行完成,在此关闭连接
$dbh = null;
?>

Many web applications benefit through the use of persistent connections to database services.

Persistent connections will not be closed at the end of the script, and is cached, when another script using the same credentials connection request is reused.

Persistent connection cache each time the script needs to avoid the overhead of establishing a new database connection with the answer, so that web applications faster.

Persistent connections

<?php
$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass, array(
    PDO::ATTR_PERSISTENT => true
));
?>

Note: If you want to use a persistent connection, you must pass an array of options to drive PDO constructor set PDO :: ATTR_PERSISTENT. If you are after the object is initialized with PDO :: setAttribute () to set this property, the driver will not use persistent connections.


PHP PDO Reference Manual PHP PDO Reference Manual