Don’t use persistent connections to MySQL in PHP

Every now and then the discussion of whether or not to use persistent connections when connection to a MySQL database server from a PHP script resurfaces. Usually, the discussion focuses on performance aspects.

Persistent connections are not closed at the end of a PHP script, but returned to a pool of open connections. When another script requires a database connection, it simply picks an idle connection from the pool. In theory, this reduces the overhead of opening and closing database connections. You can open a persistent connection to a MySQL server by using the mysql_pconnect() function instead of the traditional mysql_connect().

However, there may be some side effects. PHP scripts are executed in such a way that separate scripts have no influence on each other. Every time a PHP script is started, it starts with a blank slate. Scripts cannot influence each other. However, sharing database connections violates this principle.

Hard to debug problems ahead: for example, temporary tables are only visible in the connection that created them. Furthermore, the temporary table is automatically dropped when the connection is closed. If two PHP scripts share the same connection, they can each others’ temporary tables. One script may try to create a temporary table that already exists, or read data from that table that was meant for the other script. Comparable problems exist for prepared statements and variables.

Another problem arises when changing the connection’s encoding. If one script instance changes the encoding, suddenly several PHP scripts will communicate with the database in an unexpected encoding. Undoubtedly, this will lead to some incredibly hard to debug bugs.

Don’t use ‘em

If you want to improve your scripts’ performance by using persistent connections, you will have to keep these issues in mind. Most likely, it won’t be worth the effort or will only work if you steer away from these (extremely handy) features. Just use the newer mysqli or mysqlnd extensions if you want to improve your performance.


About this entry