Vous êtes sur la page 1sur 9

Connexions et gestionnaire de connexion Page 1 of 9

Connexions et gestionnaire de connexion

Les connexions sont établies en créant des instances de la classe de base de PDO.
Peu importe quel pilote vous voulez utiliser ; vous utilisez toujours le nom de la
classe PDO. Le constructeur accepte des paramètres pour spécifier la source de la
base de données (connue en tant que DSN) et optionnellement, le nom d'utilisateur
et le mot de passe (s'il y en a un).

Exemple #1 Connexion à MySQL

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

S'il y a des erreurs de connexion, un objet PDOException est lancé. Vous pouvez
attraper cette exception si vous voulez gérer cette erreur, ou laisser le gestionnaire
global d'exception défini via la fonction set_exception_handler() (function.set-
exception-handler.html) la traiter.

Exemple #2 Gestion des erreurs de connexion

<?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 "Erreur !: " . $e->getMessage() . "<br/>";
die();
}
?>

Avertissement

mk:@MSITStore:D:\formations\ITTP\decembre19\php_enhanced_fr.chm::/res/pdo.co... 18/01/2020
Connexions et gestionnaire de connexion Page 2 of 9

Si votre application n'attrape pas les exceptions lancées depuis le constructeur


PDO, l'action par défaut du moteur zend est de terminer le script et d'afficher une
trace. Cette trace devrait révéler des détails complets sur la connexion à la base
de données, incluant le nom d'utilisateur et le mot de passe. Il est donc de votre
responsabilité d'attraper cette exception, soit explicitement (via l'instruction catch)
ou implicitement via la fonction set_exception_handler() (function.set-exception-
handler.html).

Lorsque la connexion à la base de données a réussi, une instance de la classe PDO


est retournée à votre script. La connexion est active tant que l'objet PDO l'est. Pour
clore la connexion, vous devez détruire l'objet en vous assurant que toutes ses
références sont effacées. Vous pouvez faire cela en assignant NULL à la variable
gérant l'objet. Si vous ne le faites pas explicitement, PHP fermera automatiquement
la connexion lorsque le script arrivera à la fin.

Note: S'il existe encore d'autres références à cette instance PDO (par exemple,
à partir d'une instance PDOStatement ou d'autres variables référençant la même
instance PDO), celles-ci doivent également être supprimées (par exemple, en
affectant NULL à la variable qui référence le PDOStatement).

Exemple #3 Fermeture d'une connexion

<?php
$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
// utiliser la connexion ici
$sth = $dbh->query('SELECT * FROM foo');
// et maintenant, fermez-la !
$sth = null;
$dbh = null;
?>

Beaucoup d'applications web utilisent des connexions persistantes aux serveurs de


base de données. Les connexions persistantes ne sont pas fermées à la fin du
script, mais sont mises en cache et réutilisées lorsqu'un autre script demande une
connexion en utilisant les mêmes paramètres. Le cache des connexions
persistantes vous permet d'éviter d'établir une nouvelle connexion à chaque fois
qu'un script doit accéder à une base de données, rendant l'application web plus
rapide.

mk:@MSITStore:D:\formations\ITTP\decembre19\php_enhanced_fr.chm::/res/pdo.co... 18/01/2020
Connexions et gestionnaire de connexion Page 3 of 9

Exemple #4 Connexions persistantes

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

Note:
Si vous souhaitez utiliser des connexions persistantes, vous devez utiliser la
valeur PDO::ATTR_PERSISTENT dans le tableau des options du pilote passé au
constructeur PDO. Si vous définissez cet attribut avec la méthode
PDO::setAttribute() (pdo.setattribute.html) après l'instanciation de l'objet, le pilote
n'utilisera pas les connexions persistantes.

Note:
Si vous utilisez le pilote PDO ODBC et que votre librairie ODBC prend en charge
le bassin de connexion ODBC (unixODBC et Windows le supportent tous les
deux ; peut être plus), alors il est recommandé de ne pas utiliser les connexions
persistantes PDO, mais plutôt laisser le bassin de connexion ODBC mettre en
cache les connexions. Le bassin de connexion ODBC est partagé avec les
autres modules dans le processus ; si PDO met en cache la connexion, alors
cette connexion ne sera jamais retournée par le bassin de connexion ODBC,
faisant que plusieurs connexions sont créées pour les autres modules.

User Contributed Notes

Moshe Dolev 05-Aug-2018 01:25

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

mk:@MSITStore:D:\formations\ITTP\decembre19\php_enhanced_fr.chm::/res/pdo.co... 18/01/2020
Connexions et gestionnaire de connexion Page 4 of 9

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.

paulo dot sistema at gmail dot com 07-Feb-2017 11:29

Hello guys!
Has anyone used the ORACLE WALLET feature in PHP or Java?
https://docs.oracle.com/middleware/1213/wls/JDBCA/oraclewallet.htm#JD
BCA596
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

me+nospam at tati dot pro 11-Dec-2016 02:59

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(){

mk:@MSITStore:D:\formations\ITTP\decembre19\php_enhanced_fr.chm::/res/pdo.co... 18/01/2020
Connexions et gestionnaire de connexion Page 5 of 9

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"
}

d dot bergloev at gmail dot com 23-Nov-2016 09:38

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.

ogierschelvis at gmail dot com 25-Nov-2015 01:55

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:
(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
');

mk:@MSITStore:D:\formations\ITTP\decembre19\php_enhanced_fr.chm::/res/pdo.co... 18/01/2020
Connexions et gestionnaire de connexion Page 6 of 9

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

edsanhu at gmail dot com 06-Nov-2015 10:50

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);
?>

cappytoi at yahoo dot com 09-Apr-2014 07:08

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.

mk:@MSITStore:D:\formations\ITTP\decembre19\php_enhanced_fr.chm::/res/pdo.co... 18/01/2020
Connexions et gestionnaire de connexion Page 7 of 9

<?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());');

mk:@MSITStore:D:\formations\ITTP\decembre19\php_enhanced_fr.chm::/res/pdo.co... 18/01/2020
Connexions et gestionnaire de connexion Page 8 of 9

$pdo = null;
sleep(60);
?>
Following may be used for MYSQL: (not guaranteed)
KILL CONNECTION_ID()

thz at plista dot com 14-Jun-2013 01:27

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

alvaro at demogracia dot com 01-Jul-2011 10: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 12: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.

neville at whitespacers dot com 16-Oct-2009 03: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

mk:@MSITStore:D:\formations\ITTP\decembre19\php_enhanced_fr.chm::/res/pdo.co... 18/01/2020
Connexions et gestionnaire de connexion Page 9 of 9

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 09: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.

mk:@MSITStore:D:\formations\ITTP\decembre19\php_enhanced_fr.chm::/res/pdo.co... 18/01/2020

Vous aimerez peut-être aussi