I received an inquiry from another WordPress blogger regarding a WordPress support inquiry I had opened in August. He wrote:
I was searching for answers to a very pesky “Cannot establish connection to database!” WordPress error, and read your thread about database persistent connections. I was wondering if you could give me a hand optimizing the database for WP, I am not a programmer by any extent of the imagination, and know nothing of servers, just got one by chance. (Edited slightly by Ryan.)
Normally PHP opens a database connection when a dynamic page request comes in, uses that connection to build the webpage, and then closes the database connection once the page is finished. This is a lot of extra opening and closing which doesn’t serve any real useful purpose.
The alternative is called persistent connections. Using persistent connections, PHP keeps a pool of a database connections available for the application to use. Those connections are always open, but only in use when a page request comes in. When your request comes in, it grabs a connection from the connection pool, uses it, and then returns the connection when it’s finished. By eliminating the steps of opening and closing the connection, you save a lot of time, and a lot of processing power on the database. The drawback is that a persistent connection takes up a little bit of memory on the database server, even if no one’s ever viewing your website. There are certain situations where this may be a problem.
It’s very easy to enable persistent connections with WordPress. To do so, all you need to do is make a tiny change to the file wp-db.php inside the wp-includes directory. Open that file and search for the function “mysql_connect”. (It’s only used once.) Just change that to “mysql_pconnect” and save your changes. Presto, you’re using persistent connections!
If your site is so busy that it’s overloading the database, you may want to look into page caching instead. Caching lets WordPress build a page once a minute, or once an hour, instead of constantly rebuilding the page for every visitor. This will make your site extremely fast and dramatically cut down on the amount of memory and CPU power you need. The drawback is that new posts and comments won’t appear immediately; it will take a few minutes, depending on the setting for your cache timeout. There’s a great caching plugin for WordPress called WP-Cache which I strongly recommend.
Is anyone else out there using MySQL persistent connections with WordPress? Any tips or tricks?
