Using wpdb to connect to a separate database

I want to connect wpdb to another database. How do I create the instance and pass it the database name/username/password?

Thanks

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>";
}
echo "</ul>";

Leave a Comment