• Hi,

    I am developing a plugin and I use WordPress standard (Code Sniffer)
    But I get the following standard error on this code
    I need to know how can I use $wpdb->prepare in the following code to pass the standard?

    My code:

    $get_order = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM {$table_name} WHERE order_id = %d", $order_id ) );

    I get this error:

    Use placeholders and $wpdb->prepare(); found interpolated variable {$table_name} at "SELECT * FROM {$table_name} WHERE order_id = %d"

    “code”: “WordPress.DB.PreparedSQL.InterpolatedNotPrepared”,
    “severity”: 8,
    “message”: “Use placeholders and $wpdb->prepare(); found interpolated variable {$table_name} at \”SELECT * FROM {$table_name} WHERE order_id = %d\””,
    “source”: “PHPCS”,

    Thank you for any help

Viewing 4 replies - 1 through 4 (of 4 total)
  • Moderator bcworkz

    (@bcworkz)

    You cannot use any variables in the SQL string passed to prepare(), even {$table_name}. Instead use a placeholder %s and move $table_name to a parameter between the SQL string and $order_id.

    Thread Starter Farhad Sakhaei

    (@farhad0)

    @bcworkz
    Thank you for your reply,
    I tested that, But it seems that %s adds ‘ around the table name and that will create another SQL error !!

    Moderator bcworkz

    (@bcworkz)

    All the WP docs say to do it like this:
    $wpdb->prepare( "SELECT * FROM $table_name WHERE order_id = %d", $order_id )
    (there are normally backticks demarcating $table_name but I cannot use them like that in forum replies)

    This of course makes Code Sniffer unhappy, but there’s apparently no real need to sanitize table names. You could simply ignore the CS error. Or use %s and insert in intermediate function that replaces quotes with backticks.

    Thread Starter Farhad Sakhaei

    (@farhad0)

    @bcworkz

    Thank you,
    I found that it should be like this:

    $get_order = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM %i WHERE order_id = %d", $table_name, $order_id ) );

    %i (identifier, e.g. table/field names)

Viewing 4 replies - 1 through 4 (of 4 total)
  • You must be logged in to reply to this topic.