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
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
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 () . «
» ;
die();
>
?>?php
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.
Note: If there are still other references to this PDO instance (such as from a PDOStatement instance, or from other variables referencing the same PDO instance), these have to be removed also (for instance, by assigning null to the variable that references the PDOStatement).
Example #3 Closing a connection
$dbh = new PDO ( ‘mysql:host=localhost;dbname=test’ , $user , $pass );
// use the connection here
$sth = $dbh -> query ( ‘SELECT * FROM foo’ );
?php
// and now we’re done; close it
$sth = null ;
$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
$dbh = new PDO ( ‘mysql:host=localhost;dbname=test’ , $user , $pass , array(
PDO :: ATTR_PERSISTENT => true
));
?>?php
The value of the PDO::ATTR_PERSISTENT option is converted to bool (enable/disable persistent connections), unless it is a non-numeric string , in which case it allows to use multiple persistent connection pools. This is useful if different connections use incompatible settings, for instance, different values of PDO::MYSQL_ATTR_USE_BUFFERED_QUERY .
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.
User Contributed Notes
- PDO
- Introduction
- Installing/Configuring
- Predefined Constants
- Connections and Connection management
- Transactions and auto-commit
- Prepared statements and stored procedures
- Errors and error handling
- Large Objects (LOBs)
- PDO
- PDOStatement
- PDOException
- PDO Drivers
Php configure database connection
The MySQL server supports the use of different transport layers for connections. Connections use TCP/IP, Unix domain sockets or Windows named pipes.
The hostname localhost has a special meaning. It is bound to the use of Unix domain sockets. To open a TCP/IP connection to the localhost, 127.0.0.1 must be used instead of the hostname localhost .
Example #1 Special meaning of localhost
$mysqli = new mysqli ( «localhost» , «user» , «password» , «database» );
echo $mysqli -> host_info . «\n» ;
$mysqli = new mysqli ( «127.0.0.1» , «user» , «password» , «database» , 3306 );
echo $mysqli -> host_info . «\n» ;
The above example will output:
Localhost via UNIX socket 127.0.0.1 via TCP/IP
Connection parameter defaults
Depending on the connection function used, assorted parameters can be omitted. If a parameter is not provided, then the extension attempts to use the default values that are set in the PHP configuration file.
Example #2 Setting defaults
mysqli.default_host=192.168.2.27 mysqli.default_user=root mysqli.default_pw="" mysqli.default_port=3306 mysqli.default_socket=/tmp/mysql.sock
The resulting parameter values are then passed to the client library that is used by the extension. If the client library detects empty or unset parameters, then it may default to the library built-in values.
Built-in connection library defaults
If the host value is unset or empty, then the client library will default to a Unix socket connection on localhost . If socket is unset or empty, and a Unix socket connection is requested, then a connection to the default socket on /tmp/mysql.sock is attempted.
On Windows systems, the host name . is interpreted by the client library as an attempt to open a Windows named pipe based connection. In this case the socket parameter is interpreted as the pipe name. If not given or empty, then the socket (pipe name) defaults to \\.\pipe\MySQL .
If neither a Unix domain socket based not a Windows named pipe based connection is to be established and the port parameter value is unset, the library will default to port 3306 .
The mysqlnd library and the MySQL Client Library (libmysqlclient) implement the same logic for determining defaults.
Connection options are available to, for example, set init commands which are executed upon connect, or for requesting use of a certain charset. Connection options must be set before a network connection is established.
For setting a connection option, the connect operation has to be performed in three steps: creating a connection handle with mysqli_init() or mysqli::__construct() , setting the requested options using mysqli::options() , and establishing the network connection with mysqli::real_connect() .
The mysqli extension supports persistent database connections, which are a special kind of pooled connections. By default, every database connection opened by a script is either explicitly closed by the user during runtime or released automatically at the end of the script. A persistent connection is not. Instead it is put into a pool for later reuse, if a connection to the same server using the same username, password, socket, port and default database is opened. Reuse saves connection overhead.
Every PHP process is using its own mysqli connection pool. Depending on the web server deployment model, a PHP process may serve one or multiple requests. Therefore, a pooled connection may be used by one or more scripts subsequently.
If an unused persistent connection for a given combination of host, username, password, socket, port and default database cannot be found in the connection pool, then mysqli opens a new connection. The use of persistent connections can be enabled and disabled using the PHP directive mysqli.allow_persistent. The total number of connections opened by a script can be limited with mysqli.max_links. The maximum number of persistent connections per PHP process can be restricted with mysqli.max_persistent. Please note that the web server may spawn many PHP processes.
A common complain about persistent connections is that their state is not reset before reuse. For example, open and unfinished transactions are not automatically rolled back. But also, authorization changes which happened in the time between putting the connection into the pool and reusing it are not reflected. This may be seen as an unwanted side-effect. On the contrary, the name persistent may be understood as a promise that the state is persisted.
The mysqli extension supports both interpretations of a persistent connection: state persisted, and state reset before reuse. The default is reset. Before a persistent connection is reused, the mysqli extension implicitly calls mysqli::change_user() to reset the state. The persistent connection appears to the user as if it was just opened. No artifacts from previous usages are visible.
The mysqli::change_user() call is an expensive operation. For best performance, users may want to recompile the extension with the compile flag MYSQLI_NO_CHANGE_USER_ON_PCONNECT being set.
It is left to the user to choose between safe behavior and best performance. Both are valid optimization goals. For ease of use, the safe behavior has been made the default at the expense of maximum performance.