$wpdb-prepare : Do I have to bind a parameter to the table name?

No, you do not want to swap out the tablename. If you do, the table name will be wrapped in quotes and it will trigger a SQL error. Try:

$table = $wpdb->prefix . 'members';
$qry = $wpdb->prepare("SELECT * FROM %s", $table); 
var_dump($qry);

$qry = "SELECT * FROM $table";
var_dump($result);

The first string is invalid SQL. The second should work provided that you have a table of the correct name.

prepare() is meant to operate on user supplied data– data that could be from questionable sourced with malicious intent. You do not need to swap out data, like your table name, that is not from a questionable source.

What you want is:

$table = $wpdb->prefix . 'members';
$qry = "SELECT * FROM $table";
$result = $wpdb->get_results($qry, ARRAY_A);
var_dump($result); 

By the way, your parenthesis are wrong here (even if the rest worked):

$result = $wpdb->get_results($wpdb->prepare("SELECT * FROM %s", $table, ARRAY_A));

The ARRAY_A is an argument to the prepare and not to the get_results. It should be (though the value swapping is wrong as explained above):

$result = $wpdb->get_results(
  $wpdb->prepare("SELECT * FROM %s", $table), 
  ARRAY_A
);

Leave a Comment