1

$wpdb->prepare() is adding single quote ('') like below.

I am using below code

$sql = $wpdb->prepare("SELECT * FROM %s ",$table_name);
echo $sql;

I am getting output like below

SELECT * FROM 'wp_nametbl'

But I would like to get output like below

SELECT * FROM wp_nametbl
1

prepare() is used to escape the values for example in the WHERE-statement. Usually it is anticipated the table selection is "hardcoded". If you can't use for example $wpdb->posts or the other "table"-functions, you could whitelist the allowed tables and check if $table_name is on this white list:

<?php
    $allowed_tables = array( $wpdb->prefix . 'nametbl', $wpdb->prefix . 'nametbl2' );
    if( ! in_array( $table_name, $allowed_tables ) )
        wp_die( 'Wrong input.' );

    $sql = "SELECT * FROM " . $table_name;
?>
  • Thanks @websupporter. How can I use your code ?? What does $wpdb->prefix do ?? – Foysal Mar 31 '15 at 18:53
  • Hi Foysal. $wpdb->prefix sets the prefix for the WP database. Usually this is wp_ but since you can change it during the installation, $wpdb->prefix will choose the correct prefix. Since $wpdb is a global variable you need to use global $wpdb; in functions. More info: codex.wordpress.org/Class_Reference/wpdb – websupporter Apr 1 '15 at 19:19

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.