behold, the power of $wpdb!

the $wpdb object is crazy powerful. with it, you can access almost anything in your database

this is extremely helpful when doing plugin development…

recently at work, i was tasked to do this project:

  • create a wordpress plugin that requires a separate database table
  • the table will house data imported from several excel files
  • admin will be able to add/edit/delete entries
  • create a template that will display the data, dropdowns will help filter information: date, location
  • sort by date, then event name

$wpdb was used heavily in this plugin and it works well


then, a new request came in to have the same plugin used for another site, pulling the same data. however, this site is installed on a different database and would need to access across database.

$wpdb to the rescue

searched the wordpress support forums and found this answer from “flaminglogos.” for posterity and so i don’t lose it, i’m going to copy the code here:

Access tables in a different DB
For this case I added a new database (same server, same account) called myaccount_cities with a table called city with the columns: city.cID, city.name, city.stadium. The database username is myaccount_cityuser with a password of mypassword. Use the $wpdb class to access this table and pass the access credentials to the class using the real values for the database. The $wpdbtest_maindb->show_errors(); method makes any errors visible, which helped with debugging.

$wpdbtest_otherdb = new wpdb(
  'myaccount_cityuser',
  'mypassword',
  'myaccount_cities',
  'localhost'
);
$wpdbtest_otherdb->show_errors();
$mycities = $wpdbtest_otherdb->get_results(
  "SELECT name
  FROM city
  WHERE city.stadium = 1"
);
foreach ($mycities as $mycity) {
  echo $mycity->name . '<br />';
}

the important part to look at here is the usage of wpdb:

$wpdbtest_otherdb = new wpdb(
  'myaccount_cityuser',
  'mypassword',
  'myaccount_cities',
  'localhost'
);

that line allows the programmer to use $wpdbtest_otherdb as $wpdb to jump to a different database anywhere else.

it’s a lot cleaner than using mysql_connect() (plus, i couldn’t get it to work properly within wordpress)

Related Posts