1

I only do a SELECT on a whole table - and the table is defined in a variable:

$table = $wpdb->prefix . 'members';

Do I have to bind a parameter to this variable?

This caused an error:

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

But if I skip the "%s", this gives an error as well:

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

Should I skip "prepare" in this case?

2

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
);
0

It's just a wrong bracket closing, $wpdb->prepare only requires the query string and query parameters. Then, on get_results you can define what kind of results do you need, so:

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

Edit: you can check for $wpdb last SQL error by using this updated code

  • That code has one parenthesis too many (an extra one at the end). If I remove the last parenthesis from your code, I get no indication of error from my IDE, but there still occurs an SQL error. – Galivan Nov 11 '15 at 16:27
  • Please check updated answer – CapitanFindus Nov 11 '15 at 16:35
  • This will not work as @s_ha_dum explained. – birgire Nov 12 '15 at 9:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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