I was writing a wordpress plugin and came across a bug whereby I was creating a new database connection instance (wpdb in this case since I’m working with wordpress) everytime in a foreach loop.
foreach ($results as $result) { $newdb = new wpdb(DB_USER, DB_PASSWORD, DB_NAME, DB_HOST); ... ... }
That wasn’t a good way of connecting to a database. MySQL has a max connection limit. The default max connection value is 151 to improve performance when MySQL is used with the Apache Web server. In my example above, a “too many connection” error may occur if the’s enough elements in the foreach loop to consume all the available MySQL connections.
The easiest way to solve this problem was move the creation of the newdb connection outside of the foreach loop.
$newdb = new wpdb(DB_USER, DB_PASSWORD, DB_NAME, DB_HOST); foreach ($results as $result) { ... ... }
* You can run the command SHOW PROCESSLIST in mysqld or phpmyadmin to find out how many connections are currently opened in MySQL.
Leave a Reply