A convenient way to use $wpdb
in plugins, with custom tables and custom functions is write a class or a couple of functions that get the wp object, and configure it.
An example:
/* Return global wpdb aready setup with custom tables */
my_plugin_get_db( wpdb $wpdb = NULL ) {
static $db;
if ( is_null($db) || ! is_null( $wpdb ) ) {
$db = is_null($wpdb) ? $GLOBALS['wpdb'] : $wpdb;
}
return $db;
}
/* Setup database saving $wpdb custom table names insie wpdb object */
my_plugin_set_db() {
global $wpdb;
/* define here your custom table names */
$my_tables = array(
'my_table_1', 'my_table_1', 'my_table_1'
);
foreach ( $my_tables as $table ) {
$wpdb->$table = $wpdb->prefix . $table;
}
my_plugin_get_db( $wpdb );
}
add_action( 'plugins_loaded', 'my_plugin_set_db' );
/* Multisite compatibility? */
if ( is_multisite() ) {
add_action( 'switch_blog', 'my_plugin_set_db' );
}
After that wherever in your plugin you can use
$db = my_plugin_get_db();
$query = $db->query( "SELECT * FROM $db->my_table_1" );