Disclaimer: I’m not a Wordpress user. My knowledge about Wordpress comes from articles I googled now, some of them are really old.
wpdb
Wordpress provides wpdb
class and its global instance $wpdb
. If I get it right, this instance is used both internally and by plugins to perform all database manipulation.
Explicitly closing wpdb connection
wpdb
has no close
method. From How to close wpdb connection? at WordPress Answers:
There is no explicit method. It stores link identifier in $wpdb->dbh
field, so I guess you could use mysql_close()
on it.
It looks like Wordpress is still using the outdated mysql
API nowadays. There are three MySQL APIs in PHP now. If/when Wordpress migrates to a more recent one, inform me in comments and I’ll update this answer and the answer in the original question.
Automatic closing, persistent connections
Are you using persistent connections? They cannot be closed, they persist after the script finishes its execution.
When using non-persistent connections, they should be closed on script end. Quoting mysql_connect
function manual page:
Note:
The link to the server will be closed as soon as the execution of the script ends, unless it's closed earlier by explicitly calling mysql_close()
.
Wordpress relies on that, connections are not closed explicitly. If you want to explicitly close the connection when destroying $wpdb
, change
function __destruct() {
return true;
}
to
function __destruct() {
mysql_close($this->dbh);
return true;
}
in wp-includes/wp-db.php
.
Verifying that connections are closed
If you have a list of connections to be checked/closed, you can verify that they already have been closed by calling mysql_close
with error suppression and return value checking:
if (@mysql_close($conn)) {
echo "Closed now\n";
} else {
echo "Probably already closed\n";
}
When not having such a list, you are doomed. There is no way to list all DB connections made by the current script. You can only list all connections to a server that you have an active connection to, but not as PHP resources. If you want to close them, you can do that using KILL
statement if you have high enough privileges. Remember, though, that the connections may have been created and may be being used by other scripts.
See also