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" );

2 thoughts on “Accessing Other Databases/Servers From Within WordPress

Leave a Reply to Rafael Ehlers Cancel reply