April 14, 2013 asvignesh 0Comment

Here is the solution to fetch the data from another Database instance in word press

How To Use WPDB Class to connect and fetch data from another database host

Let’s say you’ve installed wordpress into the database wp_wordpress and you want to fetch some data from another independent database which has nothing to do with wordpress (ex. mydb). Here’s how you can do it.

Querying for Data Using WPDB

Now, here’s the trick. You have to instantiate a new WPDB instance

$mydb= new wpdb('username','password','db_name','db_host');
$rows = $mydb->get_results("select columnName from tableName");
foreach ($rows as $obj) {
echo $obj->columnName;
}

That saves you from reinventing the wheel and writing a bunch of tedious code, ex. mysql_connect, mysql_query, foreach, mysql_fetch_assoc etc just to get some data from another database.

Leave a Reply

Your email address will not be published. Required fields are marked *