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).

Пример #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().

Пример #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();
}
?>

Внимание

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.

Пример #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.

Пример #4 Persistent connections

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

Замечание: 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.

Замечание: 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.

Коментарии

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.
2008-04-17 12:37:23
http://php5.kiev.ua/manual/ru/pdo.connections.html
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_DSNPDO_USERPDO_PASSWORD);

?>
2009-10-16 06:40:17
http://php5.kiev.ua/manual/ru/pdo.connections.html
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.
2011-04-10 15:35:22
http://php5.kiev.ua/manual/ru/pdo.connections.html
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.
2011-07-01 13:07:04
http://php5.kiev.ua/manual/ru/pdo.connections.html
If you are using PHP 5.4 and later, you can no longer use persistent connections when you have your own database class that derives from the native PDO object. If you do, you will get segmentation faults during the PHP process shutdown.

Please see this bug report for more information: https://bugs.php.net/bug.php?id=63176
2013-06-14 16:27:53
http://php5.kiev.ua/manual/ru/pdo.connections.html
Using PHP 5.4.26, pdo_pgsql with libpg 9.2.8 (self compiled). As usual PHP never explains some critical stuff in documentation. You shouldn't expect that your connection is closed when you set $dbh = null unless all you do is just instantiating PDO class. Try following:

<?php
$pdo 
= new PDO('pgsql:host=192.168.137.1;port=5432;dbname=anydb''anyuser''pw');
sleep(5);
$stmt $pdo->prepare('SELECT * FROM sometable');
$stmt->execute();
$pdo null;
sleep(60);
?>

Now check your database. And what a surprise! Your connection hangs for another 60 seconds. Now that might be expectable because you haven't cleared the resultset.

<?php
$pdo 
= new PDO('pgsql:host=192.168.137.160;port=5432;dbname=platin''cappytoi''1111');
sleep(5);
$stmt $pdo->prepare('SELECT * FROM admin');
$stmt->execute();
$stmt->closeCursor();
$pdo null;
sleep(60);
?>

What teh heck you say at this point? Still same? Here is what you need to do to close that connection:

<?php
$pdo 
= new PDO('pgsql:host=192.168.137.160;port=5432;dbname=platin''cappytoi''1111');
sleep(5);
$stmt $pdo->prepare('SELECT * FROM admin');
$stmt->execute();
$stmt->closeCursor(); // this is not even required
$stmt null// doing this is mandatory for connection to get closed
$pdo null;
sleep(60);
?>

PDO is just one of a kind because it saves you to depend on 3rd party abstraction layers. But it becomes annoying to see there is no implementation of a "disconnect" method even though there is a request for it for 2 years. Developers underestimate the requirement of such a method. First of all, doing $stmt = null  everywhere is annoying and what is most annoying is you cannot forcibly disconnect even when you set $pdo = null. It might get cleared on script's termination but this is not always possible because script termination may delayed due to slow client connection etc.

Anyway here is how to disconnect forcibly using postgresql:

<?php
$pdo 
= new PDO('pgsql:host=192.168.137.160;port=5432;dbname=platin''cappytoi''1111');
sleep(5);
$stmt $pdo->prepare('SELECT * FROM admin');
$stmt->execute();
$pdo->query('SELECT pg_terminate_backend(pg_backend_pid());');
$pdo null;
sleep(60);
?>

Following may be used for MYSQL: (not guaranteed)
KILL CONNECTION_ID()
2014-04-09 22:08:21
http://php5.kiev.ua/manual/ru/pdo.connections.html
For being able to retrieve information from the db in utf-8 the connection assignment has to add to the dsn `charset=utf8`:

<?php
$dbh 
= new PDO('mysql:host=localhost;dbname=test;charset=utf8'$user$pass);
?>
2015-11-06 12:50:07
http://php5.kiev.ua/manual/ru/pdo.connections.html
As http://stackoverflow.com/questions/17630772/pdo-cannot-connect-remote-mysql-server points out; sometimes when you want to connect to an external server like this:

<?php
$conn 
= new PDO('mysql:host=123.4.5.6;dbname=test_db;port=3306','username','password');
?>

it will fail no matter what. However if you put a space between mysql: and host like this:

<?php
$conn 
= new PDO('mysql: host=123.4.5.6;dbname=test_db;port=3306','username','password');
?>

it will magically work. I'm not sure if this applies in all cases or server setups. But I think it's worth mentioning in the docs.
2015-11-25 15:55:41
http://php5.kiev.ua/manual/ru/pdo.connections.html
I would please advice people who talk about database port in reference with socket files to please read up about what a socket file is. TCP/IP uses ports, a socket file however is a direct pipe line to your database. So no, you should not replace localhost with local ip if you use a different port on your database server, because the socket file has nothing to do with your TCP/IP setup. And whenever possible, using the local socket file is much faster than establishing new TCP/IP connections on each request which is only meant for remote database servers.
2016-11-23 11:38:43
http://php5.kiev.ua/manual/ru/pdo.connections.html
If you want to keep connection after fork exit, you can kill with SIGKILL forked process.

<?php
$dbh 
= new PDO('pgsql:host=localhost;dbname=test'$user$pass);
$pid pcntl_fork();
if(
$pid == 0){
       
// forked process 'll exit immediately
       
exit;
}
sleep(1);
$statement $dbh->query('select 1');
var_dump($statement);
?>
Result: false

<?php
$dbh 
= new PDO('pgsql:host=localhost;dbname=test'$user$pass);
$pid pcntl_fork();
if(
$pid == 0){
       
// use sigkill to close process
       
register_shutdown_function(function(){
               
posix_kill(getmypid(), SIGKILL);
        });
       
// forked process 'll exit immediately
       
exit;
}
sleep(1);
$statement $dbh->query('select 1');
var_dump($statement);
?>
Result: object(PDOStatement)#3 (1) {
  ["queryString"]=>
  string(8) "select 1"
}
2016-12-11 16:59:32
http://php5.kiev.ua/manual/ru/pdo.connections.html
Hello guys!
Has anyone used the ORACLE WALLET feature in PHP or Java?

https://docs.oracle.com/middleware/1213/wls/JDBCA/oraclewallet.htm#JDBCA596

I would like to know how to implement it because I can not implement. We use PDO + PHP in all applications and now there is this demand of the DBA.

Thank you
2017-02-07 13:29:02
http://php5.kiev.ua/manual/ru/pdo.connections.html
Автор:
Please note that you cannot use persistent connections to create temporary tables in mysql/mariadb.
Tables you create using a statement like "create temporary table TABLE1 ..." are destroyed only when the mysql session ends (not php session !). This never happens if you use a persistent connection. 
If you create a temporary table on a persistent connection, the table will live even after the php script ends. The next php script that will try to issue the same create temporary table statement, will receive an error.
IMHO, this fact makes persistent connections quite useless.
2018-08-05 16:25:09
http://php5.kiev.ua/manual/ru/pdo.connections.html
It's not possible to use a persistent connection and to extend the PDOStatement class to add methods to the standard class. This means that you cannot do:

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

This results in an error:

Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[HY000]: General error: PDO::ATTR_STATEMENT_CLASS cannot be used with persistent PDO instances
2020-03-03 17:56:58
http://php5.kiev.ua/manual/ru/pdo.connections.html

    Поддержать сайт на родительском проекте КГБ