6

Is there any method to close connection similar to mysql_close() for $wpdb in WordPress?

Is it not necessary to close connection for global $wpdb?

3 Answers 3

6

You don't have to worry about closing connection to you DB because it will be automatically closed when a request will be processed by your server.

But if you have to close it, then you can do something like this:

@mysql_close( $wpdb->dbh );

Pay attention that it could lead to unexpected results because other plugins could rely on this connection.

1
  • its not really close. there is too many sleep connection. Commented Mar 27, 2018 at 19:35
5

I don't think wpdb actually cares to have a way for explicitly closing connection.

From search through code base the WP's unit tests (not actual core code) are doing the following (note the difference in API used since latest WP versions):

if ( $wpdb->use_mysqli ) {
    mysqli_close( $wpdb->dbh );
} else {
    mysql_close( $wpdb->dbh );
}
unset( $wpdb->dbh );
4

$wpdb is a global instance of the wpdb class. That class is what creates the database connection and that single database connection is reused repeatedly by the WordPress Core, as well as by most plugins, and themes. You don't want to close it. If you look at the source for wpdb there isn't even a method provided within the class to kill the connection.

The only time I would close a wpdb connections would be for connections you've created, and never for the $wpdb instance, and then you will have to follow the pattern suggested by @EugeneManuilov:

$mydb = new wpdb(DB_USER, DB_PASSWORD, DB_NAME, DB_HOST);
@mysql_close( $mydb->dbh ); 

That is likely to be a bit squirrelly in itself because the $mydb object doesn't really know that the connection is gone. You've reached in and pulled the carpet out from under it without really resyncing things. The object isn't meant to function like that. I'd probably explicitly kill the object afterwards with unset($mydb);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.