When establishing a connection to a database using PDO, should the PDO attribute PDO::ATTR_PERSISTENT be used every time? It says that this creates a persistant connection for that user, and will grab that same connection instead of re-establishing a new one each time you ask for a database connection. Why isn't this the default? Is there any reason not to use it?
The biggest drawback to persistent connections is that it limits the number of users you can have browsing your site: if MySQL is configured to only allow 10 concurrent connections at once then when an 11th person tries to browse your site it won't work for them. PDO does not manage the persistence.
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.
mysql_pconnect() acts very much like mysql_connect() with two major differences. First, when connecting, the function would first try to find a (persistent) link that's already open with the same host, username and password. If one is found, an identifier for it will be returned instead of opening a new connection.
The idea behind persistent connections is that a connection between a client process and a database can be reused by a client process, rather than being created and destroyed multiple times.
If you don't handle transaction correctly, it can lead to a "new" persistent connection already in a transaction, which can cause chaos.
Just one simple case caused by the following code:
<?php $pdo = getCustomPersistantPDO(); $pdo->beginTransaction(); if( rand() % 2 === 0 ) { //simulate a poorly handled error exit(); } $pdo->commit(); ?>
Request 1:
(starts w/o a transaction open) openTransaction incorrectly handled error (never closes transaction)
Request 2:
(start w/ a transaction open, because it was not closed in the previous connection.) openTransaction -> fails due to already open
BTW the correct version of example is:
<?php $pdo = getCustomPersistantPDO(); $pdo->beginTransaction(); if( rand() % 2 === 0 ) { //simulate a correctly handled error $pdo->rollBack(); exit(); } $pdo->commit(); ?>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With