You have the following methods of the $wpdb
object:
-
$wpdb->flush()
that contains a call tomysqli_free_result()
ormysql_free_result()
if not supported. -
$wpdb->check_connection()
that contains a call tomysqli_ping()
ormysql_ping()
if not supported.
You can of course use all your PHP functions in WordPress.
Here’s an example based on the \wpdb
class itself:
// Use the global instance created by WordPress
global $wpdb;
// Fetch our data with some huge query:
$results = $wpdb->get_results( "SELECT * FROM {$wpdb->posts}" );
// ... some data handling here
// Let's flush for another huge query.
// But that's not actually needed,
// since this is already done in the $wpdb->query() call
// that's used within the $wpdb->get_results() method.
$wpdb->flush();
// Check the connection:
if( ! $wpdb->check_connection( $allow_bail = false ) )
{
// Let's try to connect again, but there has already been
// reconnection retries within the check_connection() method above.
// Here we handle the bail manually:
// Check the connection:
if( ! $wpdb->check_connection( $allow_bail = false ) )
{
// Let's try to connect again, but there has already been
// reconnect retries within the check_connection() method above.
// Here we handle the bail manually:
if( ! $wpdb->db_connect( $allow_bail = false ) )
{
// Exit with a style:
if ( did_action( 'template_redirect' ) )
{
die( __( 'No DB connection' ) );
}
else
{
wp_load_translations_early();
$wpdb->bail( sprintf( '<pre>%s<pre>', __( 'No DB connection' ) ) );
}
// Just in case:
dead_db();
}
}
}
// Fetch another set of data:
$results = $wpdb->get_results( "SELECT * FROM {$wpdb->users}" );
Notice that in most cases, we don’t need to create custom SQL queries with $wpdb
.
We can get very far by simply using the WP_Query
, WP_Comment_Query
or WP_User_Query
classes. They can help us generate complex SQL queries that are executed through the included $wpdb->get_results()
or $wpdb->get_col()
calls.
For the WP_Query
case, this happens in the humongous WP_Query::get_posts()
method.
So there we already have $wpdb->flush()
calls.