Scotts Web Dev Banner
Did you notice... every article on this site has an associated video? Consider subscribing to Scotts Web Dev on YouTube! :)

Connect To Two Databases In WordPress

Think About Why You Need Two Databases In WordPress

This is one of those situations where you may be trying to solve a problem in a wrong way. There are only a few very basic scenarios where you need to connect to multiple databases in the same script.

Is there a different way to tackle your problem?

Plausible Scenarios For Two Databases In WordPress

Here are the reasons I can think of where connected to two databases would make sense. If you can think of more, please comment in the YouTube Video above.

  • Connecting to a remote database
  • Connecting to a slave database
  • Pulling data from one database, manipulating it, and inserting it into another database

Let’s Connect To Multiple WordPress Databases

The first database connection, your current connection, is already available to you in the variable $wpdb. Depending on your scope, you may need to make $wpdb global by using:

global $wpdb;

or by passing it into your function or class.

You can then assign a variable to your current local database.

global $wpdb;
$db1 = $wpdb;

Now, all we need is the second database. The second database connection can be accomplished by using a new wpdb class instance.

The class takes 4 parameters to it’s constructor. Those parameters are database username, database username password, database name, and host name.

Have the parameters ready and assign your second database connection to a variable like this (replacing data with real data):

$db2 = new wpdb('db_user', 'db_user_pass', 'db_name', 'host_name');

You Can Now Operate On Each Database Separately

Use $db1 and all of it’s methods (like query(), prepare(), get_results(), etc) and do the same with $db2. They are completely separate databases with separate instances.

You can even pull from the second database, manipulate the contents, and then insert it into the local current database. I had to do this recently for work.

Hope this is helpful! Leave a comment on the video and subscribe to my YouTube Channel.

Ever been interested in learning PHP? You can learn the basics of PHP, for beginners, in 18 minutes!