WordPress – Accessing external database

December 23, 2014 by Pat - Comments - - 1 min read

WordPressI wanted to post this quick tip on how to access an external database, or an external table, from within WordPress. This is mostly here for my reference in case I need it in the future. Hopefully it helps you out, too.

I have a table that’s external to my primary WordPress installation that I needed to get some information out of. In my functions.php, I added this piece of code into a function I already had, and it worked great.

It’s a simple bit of code that just counts the number of entries in the “data” table. This snippet uses the the database login and password information from your wp-config.php. If you need to specify different login information, just change the DB_USER and DB_PASSWORD to your values.

// Setup external database call
$externalTable = new wpdb(DB_USER, DB_PASSWORD, 'tablename', 'localhost');
$exTable = $externalTable->get_results("SELECT * FROM data");
$dataCount = count($data);
Disclosure: Some of the links on this website are affiliate links. This means that, at zero cost to you, I will earn an affiliate commission if you click through the link and finalize a purchase.
Share this post: