Should plugins close $wpdb via $wpdb->close()
-
Hello,
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?
Or is it sufficient to simply close out the prepared statement, and flush the connection, but allow $wpdb to maintain its connection.i.e., Should I execute this before every call to $wpdb
$wpdb->check_connection();
To re-establish the connection if required.
And then follow up after I’m done with calls to close the connection:function my_close_statement($statement) { try { if (!empty($statement)) { $statement->free_result(); $statement->close(); } } catch (Exception $e) { } } function my_close_database($dbconn, $statement=null) { my_close_statement($statement); try { if (!empty($dbconn)) { $dbconn->flush(); $dbconn->close(); } } catch (Exception $e) { } }
Additional Info: My reason for asking is that I am worried that I am not cleaning statements/results/connections up properly, and that this may be causing issues with Yeost, and JetPack. I’m seeing a lot of these in my debug log:
“WordPress database error Commands out of sync; you can’t run this command now for query SELECT”
Which appear to be Yeost and Jetpack complaints.
- The topic ‘Should plugins close $wpdb via $wpdb->close()’ is closed to new replies.