Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should PDO::ATTR_PERSISTENT be used every time? [duplicate]

Tags:

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?

like image 385
dqhendricks Avatar asked May 13 '11 18:05

dqhendricks


People also ask

What are the disadvantages of using persistent connection in PDO?

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.

What is PDO persistent connection?

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.

Which function gives persistent connection with database?

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.

What is persistent connection MySQL?

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.


1 Answers

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();  ?> 
like image 62
Kendall Hopkins Avatar answered Nov 23 '22 14:11

Kendall Hopkins