Accessing Other Databases/Servers From Within WordPress

Say you have a WordPress install where you need to pull in data from a separate database or server. The normal $wpdb instance of the wpdb class is limited to the database that your WordPress tables are located in. Yes, you could use mysql_connect() and the other standard PHP database functions, but then you don’t get all of the WordPress magic. So what to do?

The answer is surprisingly simple: make a new instance of the wpdb class! Dion Hulse (DD32) was kind enough to point out this great solution to me a few weeks back and I thought it was worth sharing with you all.

$myotherdb = new wpdb( $dbuser, $dbpassword, $dbname, $dbhost );

$myotherdb->get_results( "SELECT id, name FROM mytable" );

So Apparently WordPress Can Guide Missiles

First off, all credit goes to DD32 for this. He spotted it and I’ve been laughing ever since at how funny this is.

The following screenshots are from episode 5 of the British mini-series Strike Back:

If you don’t recognize the code, it’s from one of WordPress’ Javascript files called post.js.

Mark Jaquith was even kind enough to port their changes back into the WordPress core. Hilarious.