Wordpress - Using wpdb to connect to a separate database
Yes it's possible.
The wpdb object can be used to access any database and query any table. Absolutely no need to be Wordpress related, which is very interesting.
The benefit is the ability to use all the wpdb classes and functions like get_results
, etc so that there's no need to re-invent the wheel.
Here's how:
$mydb = new wpdb('username','password','database','localhost');
$rows = $mydb->get_results("select Name from my_table");
echo "<ul>";
foreach ($rows as $obj) :
echo "<li>".$obj->Name."</li>";
endforeach;
echo "</ul>";
Connecting to a second database is easy in WordPress, you simply create a new instance of the WPDB class and use it the same way you would use the standard $wpdb instance we all know and love.
Assuming the second database has the same login information as the main WP one you can even use the predefined constants from wp-config.php to avoid hardcoding the login information.
/**
* Instantiate the wpdb class to connect to your second database, $database_name
*/
$second_db = new wpdb(DB_USER, DB_PASSWORD, $database_name, DB_HOST);
/**
* Use the new database object just like you would use $wpdb
*/
$results = $second_db->get_results($your_query);
no one has said this so I thought I'd add an even easier way..
as long as your additional database has the same user/pass details to access it as your wordpress database you can use the database name before the table name like this
$query = $wpdb->prepare('SELECT * FROM dbname.dbtable WHERE 1');
$result = $wpdb->get_results($query);