WordPress-Coding-Standards
WordPress-Coding-Standards copied to clipboard
SQL queries should not use hardcoded table names
Is your feature request related to a problem?
Using hardcoded table names in SQL queries causes problems for multisite installations, or users who have changed the default table prefix.
Describe the solution you'd like
Queries that do not use the $wpdb->prefix to determine table names, should trigger a CS error.
$wpdb->prepare( "SELECT * FROM wordpress.wp_posts WHERE id = %d", $id);
Additional context (optional)
see also (loosely related) https://github.com/WordPress/WordPress-Coding-Standards/issues/1589
Marked as valid feature request.
Some notes:
- The sniff should look for
FROM, but also forLEFT JOINand other variants of that. Needs some investigation in the MySQL manual to find every keyword the sniff should look for. The sniff will probably need to strictly look for the uppercase keywords used in text strings, but that will be prone to false positives. - I think the sniff should verify that table names are not 100% hard-coded, but that the first part is always dynamic. I know there are quite some plugins which abstract things out a bit more, which could result in
$this->wpdb->prefixor$this->get_table_prefix(). The sniff should probably differentiate in error code for these, likeTableNameHardCodedandTableNamePrefixNotUsingWpdb. Plugins/themes using extra abstractions could then ignore the second error code from their custom ruleset. - For the "standard" WP table names, the sniff should probably trigger an error if these are not 100% dynamic, i.e.
$wpdb->posts, not$wpdb->prefix . 'posts' - This sniff would need lots and lots of tests as queries can be build up in so many different ways (concatenation, prepared queries, interpolation etc) and the sniff would need to try and detect this issue in as many situations as possible with a minimum of false positives.
+1 for this request, we just faced a bug with hardcoded prefixes and this would have helped.