I have defined my database table names as constants in a base class and use them throughout my code.
protected const MAP_KEY_TABLE = 'eds_map_keys';
If I use them like this I get a warning to use place holders.
$keys = $wpdb->get_results(
'SELECT * FROM ' . self::MAP_KEY_TABLE . ' WHERE key_type = "map_key"',
OBJECT
);
$mapkey = $keys[0]->key_value;
if I use place holders like this:
$keys = $wpdb->get_results(
$wpdb->prepare(
'SELECT * FROM %1s WHERE key_type = "geo_key";',
self::MAP_KEY_TABLE
),
OBJECT
); // db call ok.
$map_key_geo = $keys[0]->key_value;
I get a warning that: "message": "Complex placeholders used for values in the query string in $wpdb->prepare() will NOT be quoted automagically. Found: %1s."
As suggested in a comment I tried $1$s but the warning still persists.
WP Version 6.1.1, PHP Version 8.0.18, PHP_CodeSniffer version 3.7.1
I don't know if the guidelines are version specific but they were installed like this.
composer require --dev wp-coding-standards/wpcs
composer require --dev dealerdirect/phpcodesniffer-composer-installer
I'd really like to get rid of the messages about coding style but have been stuck on this one for a while. Any suggestions greatly appreciated.
WHERE key_type = '$type'
). And you could also instead assign the table name to a local variable and then use"SELECT * FROM $table WHERE key_type = 'map_key'"
?%1$s
(note the$
) and not%1s
, which is what you used. (yes,%1s
may have worked for you, but that does not mean it's correct)phpcs
andwpcs
(I thought those were warnings added by WordPress to the debug log likewp-content/debug.log
), and apparently, you need to do$wpdb->eds_map_keys = self::MAP_KEY_TABLE;
(in the class constructor), which then allows these queries:"SELECT * FROM $wpdb->eds_map_keys WHERE key_type = 'map_key'"
and$wpdb->get_results( $wpdb->prepare( "SELECT * FROM $wpdb->eds_map_keys WHERE key_type = %s", 'map_key' ) );
, without getting those "Complex placeholders" warnings.FROM $wpdb->eds_map_keys
,FROM $table
andFROM ' . self::MAP_KEY_TABLE . '
are the same (the table names could all be considered not safe).. so maybe it'swpcs
which is being a little too strict... anyway, see Ignoring Parts of a File and Whitelisting code which flags errors, and be sure to tag me if you replied or edited your post :)