Should close $wpdb via $wpdb->close()

I’ve been writing a few custom plugins for my site and I was wondering about the correct way to interact with $wpdb.
My plugin executes a few queries using the global $wpdb connection.
I noticed that a $wpdb->close(); method has been added to WordPress, to close the database connection object.

My question is: Should a plugin close out the connection after executing queries?

I have been searched on the folder of some famous plugin(like rank math, Yoast). they use $wpdb a lot but I could not find $wpdb->close() on their code. I mean at the end of their function they do not close query.

for example, I have been writing a function for counting post from last week

    function get_posts_count_from_last_week($post_type = 'post')
 {
        global $wpdb;
        $numposts = $wpdb->get_var($wpdb->prepare("SELECT COUNT(ID) " . "FROM " . $wpdb->posts . " WHERE post_status='publish' AND post_type= %s AND post_date> %s", $post_type, date('Y-m-d H:i:s', strtotime('-168 hours'))));
        return $numposts;

}

I get a lot of “WordPress database error Commands out of sync; you can’t run this command now for query SELECT”
So I have to put $wpdb->close(); before return and after that I did not get Commands out of sync at all.

I confuse, why I have to close the connection when other plugins don’t do that!
by the way in my theme I have some functions with global $wpdb but, again there is not any $wpdb->close() for closing.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

The close() function was added for completeness in the database abstraction. If the database is prematurely closed in a plugin or theme (as you are using it), the next call to wpdb::query() will re-open the connection.

Your Commands out of sync error is a MySQL error, not a WordPress one, and it might be coming from a plugin or theme that you’re using. Googling for wordpress database commands out of sync comes up with a lot of possible issues, including caching plugins. Try disabling all plugins and switching to a default theme (like Twenty Twenty); if the issue goes away, turn plugins back on till you find the culprit. Then contact that plugin’s support crew.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x