WordPress: Query Any Table in the DB

WordPress LogoOne of the first things I learned when working with WordPress is how to query the database.  More specifically, how to query custom tables within the WordPress database.  Sure, in the loop you can pull user and post/page information quite easily, but what if your plugin stores custom data?  Exactly.

It’s quite simple, really.

 global $wpdb;  // Bring our DB connection in scope
$table_prefix = $wpdb->prefix; // Get the WP table prefix
$table_name = "mytablename"; // Assign the table name we wish to query
$table = $table_prefix . $table_name; // Put it all together
$queryresult = $wpdb->get_results("SELECT * FROM " . $table . " WHERE id = " . $id . " LIMIT 1"); // And query the DB

As the comments say, we get our DB connection via $wpdb, then we build our table name, and finally run our query.  In this case, I’m selecting one item by ID.  Of course, you could write this in far fewer lines, this is just to show the entire process.

Let’s go ahead and write out a shortened version for kicks.

global $wpdb;
$queryresult = $wpdb->get_results("SELECT * FROM " . $wpdb->prefix . "mytablename WHERE id = " . $id . " LIMIT 1");

And we’ve successfully turned five lines in to two!

4 thoughts on “WordPress: Query Any Table in the DB

Comments are closed.