Alex Rivera | Logout

MySQL Database Connection Management In PDO

Asked 2012-08-22T02:17:54.487
10

I'm very new to PHP/MySQL and I'm learning things as I go. One of the newer things I've learned is that there is a maximum number of connections that can be made to a database for a given username. When I first started building my website on Wordpress, I was using the old mysql_query() commands. I never had to make a connection to the MySQL database because Wordpress keeps an active connection just by being logged in on the website. When I decided to switch all my MySQL queries over to the PDO extension, I could no longer take advantage of Wordpress' active connection, and had to start my own database connections. I did this in a separate PHP config file that I included in every page that ran a script. The PHP code looks like this:

try {
    $DBH = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass);
}
catch(PDOException $e) {  
    echo "Select DB Error: " .$e->getMessage(). "</br>";
}

Unfortunately now, I constantly get the following error:

" SQLSTATE[42000] [1203] User already has more than 'max_user_connections' active connections"

Based on some online research, I tried various different methods to fix this. First, I tried to set the database connection to null at the end of each script (though this should be PHP PDO's default?). Then I tried to set each statement handle to null after each query of the database (this was a hopeless endeavor). And finally, I tried using a persistent connection by changing the following line in my config file:

$DBH = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass, array(PDO::ATTR_PERSISTENT => true));

None of this seems to work and I still get the same exact error. The site, when ready, needs to be able to handle 100-200 people per day entering a myriad of different data. Even if I can figure out how to take advantage of Wordpress' active connection using PDO, that would be a good start. I'd appreciate any

Edit
Report

1 Answer

1

Using include_once('config.php') or require_once('config.php') in the files instead of include 'config.php' may be your solution to avoid duplicate database connections.

answered 2012-08-27T05:33:36.613

Your Answer