Data from another Database – WordPress

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.

Default image
Vignesh A Sathiyanantham
AWS Certified developer with 8 years of extensive experience working for Cloud and Datacenter solutions and leading a small team in a lean startup based on Bangalore, India

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.