0

I am writing plugins that connects to an external database, connecting to the external database using the wpdb class:

$mydb = new wpdb('username','password','database','localhost');
$rows = $mydb->get_results("select Name from my_table");

I want to have multiple plugins on a single page, all connecting to the same external database, but different tables.

If I try to have multiple plugins on a page, the first one works, but the ones underneath draw an error:

fatal error call to a member function get_results() on null

I tried to flush the connection to no avail. Besides creating a new $mydb for each plugin, is there a way to utilize the one class, but across different plugins? I've also tried global $mydb in the plugins underneath the first one but does not work.

Thanks!

  • Not all databases support external connections, are you sure this one does? – Jacob Peattie Oct 23 '17 at 23:58
1

You'll have to make the variable global when you define it, e.g.

global $mydb;
$mydb = new wpdb('username','password','database','localhost');

and then use global $mydb; in the other plugins. Aside from theme files, functions.php, and plugins while being loaded, pretty much nothing in WP runs in global context, so if you need to access global variables, you'll have to use global.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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