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
If you have used the wordpress global variable $wpdb before, querying for data is nothing different from what you’ve done previously.
Now, here’s the trick. You have to instantiate a new WPDB instance 🙂
$mydb= new wpdb('user','pass','mydb','localhost'); $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.
reisa says
and where i must edit the script?
David says
unless you’re writing a custom wordpress plugin connecting to a different database other than your wordpress db, you won’t need to edit anything
Dave Warfel says
Does this work with MSSQL databases, or only MySQL ones?
David says
Dave, don’t think it’s possible to connect to MSSQL with wpdb – check this http://codex.wordpress.org/Function_Reference/WP_Query
Dave says
Thanks David. Appreciate the response.
Jeshal M Brahmbhatt says
Hello i have similar question to use external database for my e-commerce project and i didn’t want to get data from the wp database but use of external database, because i create android version of that project and i want one database to update, delete and fetch the data for my project(wordpress website, Android Application). It is possible in this way you mention $wpd global or other thing i do for that . Please help me out for this.Thanks in advance