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);
Share this post:

About Pat

I'm an I.T. systems engineer by day and in my spare time I code. I've made WordPress websites and plugins, weewx extensions and static html sites using Jekyll. I'm a technologist at heart and I enjoy tinkering on many different technology projects. Here on my site you will find some of the projects I've worked on, and other random bits of knowledge that I hope help someone along the way.