Tags

In WordPress wpdb is the class which handling all the database related tasks. In default WordPress installation we have $wpdb object of that class using which we are doing database related tasks like INSERT, UPDATE, DELETE etc. But here the restriction is that we can do these tasks within the database in which WordPress is installed. Means using $wpdb you can not do any database query in which WordPress is not installed.

wordpress-multiple-mysqlBut now a days it is very frequent requirement from clients that your WordPress code needs to talk with multiple database and when we are getting this kind  requirement for the first time we are thinking ahh how it can be done. But after some Google you get to know that this is not a big deal as WordPress wrote wpdb class in such a nice way that you can create any number of object for different database connection. So the idea is WordPress created $wpdb object to talk with the database in which WordPress installed similarly, you can create other object of the same class to do the sql operations in different database.

Let us see code example:

$newdb = new wpdb( 'USERNAME' , 'PASSWORD' , 'DATABASE NAME' , 'HOST' );

Here we are establishing the connection with new database.

Now using this object you can do whatever you want to do with this new database. Like

$results = $newdb->get_results( "SELECT <SOME FIELDS> FROM <TABLE NAME> WHERE <SOME CONDITION>" );
foreach ( $results as $result ) {
echo $result->fieldname;
}

Happy multiple connection…

Advertisements