Can’t pass table to $wpdb->prepare

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?

2 Answers
2

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

Leave a Comment