WordPress: Query Any Table in the DB

426th Aug 2010Wordpress, , , , , , ,

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.

1
2
3
4
5
 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.

1
2
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 Comments Comments Feed

  1. Sam Najian (May 11, 2011, 5:10 pm). Reply

    thanks for the great guide .
    keep rocking

  2. Rahat Hossen (January 11, 2014, 1:02 pm). Reply

    Can you tell me where is add this code ?

    • Anthony G. Cyphers (January 24, 2014, 1:45 am). Reply

      This code would be placed in your plugin or theme files, and would vary greatly based upon your project’s organization.

Add a Comment

Before you post, please prove you are sentient.

what is 9 plus 6?