PDO
在线手册:中文 英文
PHP手册

Connections and Connection management

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=test'$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=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();
}
?>

Warning

If your application does not catch the exception thrown from the PDO constructor, the default action taken by the zend engine is to terminate the script and display a back trace. This back trace will likely reveal the full database connection details, including the username and password. It is your responsibility to catch this exception, either explicitly (via a catch statement) or implicitly via set_exception_handler().

Upon successful connection to the database, an instance of the PDO class is returned to your script. The connection remains active for the lifetime of that PDO object. To close the connection, you need to destroy the object by ensuring that all remaining references to it are deleted--you do this by assigning NULL to the variable that holds the object. If you don't do this explicitly, PHP will automatically close the connection when your script ends.

Example #3 Closing a connection

<?php
$dbh 
= new PDO('mysql:host=localhost;dbname=test'$user$pass);
// use the connection here


// and now we're done; close it
$dbh null;
?>

Many web applications will benefit from making persistent connections to database servers. Persistent connections are not closed at the end of the script, but are cached and re-used when another script requests a connection using the same credentials. The persistent connection cache allows you to avoid the overhead of establishing a new connection every time a script needs to talk to a database, resulting in a faster web application.

Example #4 Persistent connections

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

Note:

If you wish to use persistent connections, you must set PDO::ATTR_PERSISTENT in the array of driver options passed to the PDO constructor. If setting this attribute with PDO::setAttribute() after instantiation of the object, the driver will not use persistent connections.

Note:

If you're using the PDO ODBC driver and your ODBC libraries support ODBC Connection Pooling (unixODBC and Windows are two that do; there may be more), then it's recommended that you don't use persistent PDO connections, and instead leave the connection caching to the ODBC Connection Pooling layer. The ODBC Connection Pool is shared with other modules in the process; if PDO is told to cache the connection, then that connection would never be returned to the ODBC connection pool, resulting in additional connections being created to service those other modules.


PDO
在线手册:中文 英文
PHP手册
PHP手册 - N: Connections and Connection management

用户评论:

alvaro at demogracia dot com (01-Jul-2011 06:07)

On connection errors, the PDO constructor seems to do two things no matter your PDO::ATTR_ERRMODE setting:

1. Trigger a warning
2. Throw a PDOException

If you set the PDO::ATTR_ERRMODE parameter, it will only take effect on further operations.

jak dot spalding at gmail dot com (10-Apr-2011 08:35)

Just thought I'd add in and give an explanation as to why you need to use 127.0.0.1 if you have a different port number.

The mysql libraries will automatically use Unix sockets if the host of "localhost" is used. To force TCP/IP you need to set an IP address.

ekkart at ekkart dot de (14-Oct-2010 11:43)

In order to set the encoding of the database connection, use the exec function:
<?php
try {
   
$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
   
$dbh->exec("SET CHARACTER SET utf8");
   
$dbh = null;
} catch (
PDOException $e) {
    print
"Error!: " . $e->getMessage() . "<br/>";
    die();
}
?>

angela (06-Apr-2010 10:53)

I spent hours today trying to get my portable wamp to update a database, using localhost:800 and port 3307 for mysql. For it to work I needed to adjust the connect() instruction as described:
$dsn = "mysql:host=127.0.0.1;port=3307;dbname=mydatabase";

neville at whitespacers dot com (16-Oct-2009 11:40)

To avoid exposing your connection details should you fail to remember to catch any exception thrown by the PDO constructor you can use the following class to implicitly change the exception handler temporarily.

<?php

Class SafePDO extends PDO {
 
        public static function
exception_handler($exception) {
           
// Output the exception details
           
die('Uncaught exception: ', $exception->getMessage());
        }
 
        public function
__construct($dsn, $username='', $password='', $driver_options=array()) {

           
// Temporarily change the PHP exception handler while we . . .
           
set_exception_handler(array(__CLASS__, 'exception_handler'));

           
// . . . create a PDO object
           
parent::__construct($dsn, $username, $password, $driver_options);

           
// Change the exception handler back to whatever it was before
           
restore_exception_handler();
        }

}

// Connect to the database with defined constants
$dbh = new SafePDO(PDO_DSN, PDO_USER, PDO_PASSWORD);

?>

dan dot franklin at pearson dot com (17-Apr-2008 05:37)

Note that you can specify a port number with "port=####", but this port number will be ignored if the host is localhost.  If you want to connect to a local port other than the default, use host=127.0.0.1 instead of localhost.