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?
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?
HTH
you need to register the table with the $wpdb class so that you could use something like:
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:
http://snipplr.com/view/52178/
This is the important code you need in that function, (edited a bit my me) for those that are interested in just that: