WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I'm having trouble passing a table variable to $wpdb->prepare(); Here is functioning code:

$table = $wpdb->get_blog_prefix( $blog_id ) . 'my_table';

$voters = $wpdb->get_row($wpdb->prepare("SELECT * FROM $table WHERE user_id= %d AND post_id = %d;", $user_ID, $post->ID  ));

This works great. However I think I should also be including my table in the prepare statement. But, it breaks when I change it to this:

$table = $wpdb->get_blog_prefix( $blog_id ) . 'my_table';

$voters = $wpdb->get_row($wpdb->prepare("SELECT * FROM %s WHERE user_id= %d AND post_id = %d;", $table, $user_ID, $post->ID  ));

Any ideas on why it might be breaking?

share|improve this question
up vote 2 down vote accepted

The prepare() method escapes %s. The second piece of code you listed breaks because quotation marks are added to the table name, hence it doesn't match what's in the DB.

The first piece of code works because it's a straight string replacement hence matching the name of the table in the database.

What is the error message you are getting?


share|improve this answer
For anyone's future reference, it appears I was wrong. In keeping with the examples in the codex it appears that I do NOT need to include the table in the prepare statement. Also @rxn is correct as to why this wasn't working. – Nick Budden Aug 14 '11 at 16:03

you need to register the table with the $wpdb class so that you could use something like:

$table = $_POST['table'];
$res = $wpdb->get_results($wpdb->prepare("
SELECT * FROM {$wpdb->my_custom_table}
WHERE user_id= %d AND post_id = %d;",
array($user_ID, $post->ID  )

Here's a link to nice function, that when called in init will create your table if it doesn't exist, but will always register it under what ever name you like:


This is the important code you need in that function, (edited a bit my me) for those that are interested in just that:

//include the wordpress db functions
require_once(ABSPATH . 'wp-admin/upgrade-functions.php');

    if (!isset($wpdb->custom)) $wpdb->custom = new stdClass();
    //add the shortcut so you can use $wpdb->custom->my_table
    $wpdb->custom->$search_table = $search_table;
    $wpdb->tables[] = str_replace($wpdb->prefix, '', $search_table);
share|improve this answer
You wouldn't want to add to the $wbdb object. A) It makes no difference to not retrieving it from the object and B) you're filling something that doesn't belong there into a global WP object. – kaiser Nov 16 '12 at 11:49

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.