WordPress: How can we use WPDB Class To Connect and Fetch Data From Another Database?

How can we use WPDB Class To Connect and Fetch Data From Another Database?

Solution:

Let us say we have installed wordpress into the database wp_wordpress and we want to fetch some data from another independent database which has nothing to do with wordpress .

Here is how you can do it.

Query to Data Using WPDB

If we have used the wordpress global variable $wpdb before, querying for data is nothing different from what we have done previously.

Now, here is the trick. we have to instantiate a new WPDB instance.

 
$mydb = new wpdb('username','password','database','localhost');
$rows = $mydb->get_results("select Name from my_table");
echo "
    "; foreach ($rows as $obj) : echo "
  • ".$obj->Name."
  • "; endforeach; echo "
";

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.

No comments:

Post a Comment