WordPress – Accessing external database
I 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');
$externalTable->show_errors();
$exTable = $externalTable->get_results("SELECT * FROM data");
$dataCount = count($data);