WordPress-Coding-Standards icon indicating copy to clipboard operation
WordPress-Coding-Standards copied to clipboard

Add a check to verify that the `%i` placeholders are used only for identifier names.

Open craigfrancis opened this issue 3 years ago • 0 comments

Following up on PR #2072, and suggested by Juliette.

This would need additional research to work out how to reliably distinguish identifier names from values, could possibly, partially be done by looking for an SQL keyword before it, partially by looking for placeholders within backticks.

This is a nice idea, and I'm not saying it can't be done, I just worry that it might get a bit complicated.

I've got some (slightly contrived) examples below showing where Identifiers could be used:

$wpdb->prepare( 'SELECT %i FROM %i.%i ORDER BY %i', 'field', 'database', 'table', 'field' );
$wpdb->prepare( 'SELECT COUNT(%i) AS c', 'field' );
$wpdb->prepare( 'SELECT CONCAT(%i, " ", name_last)', 'name_title' );
$wpdb->prepare( 'SELECT IF(%i = "publish", 1, 0) AS %i', 'post_status', 'published' );
$wpdb->prepare( 'SELECT * FROM %i AS a LEFT JOIN %i AS b ON ...', 'table_1', 'table_2' );
$wpdb->prepare( 'INSERT INTO %i SELECT * FROM %i', 'table_1', 'table_2' );

$wpdb->prepare( '
    SELECT
        *
    FROM
        (
            SELECT
                %i AS t,
                MAX(%i) AS d
            FROM
                %i
            GROUP BY
                %i
        ) AS a
    ORDER BY
        LENGTH(%i)',

    'post_type',
    'post_date',
    'wp_posts',
    'post_type',
    't'
);

$wpdb->prepare( '
    WITH
        %i AS (SELECT id, %i as f1 FROM %i),
        %i AS (SELECT id, %i as f1 FROM %i)
    SELECT
        t.id,
        t.f1
    FROM
        %i AS t',

    'with_1',
    'post_title',
    'wp_posts',
    'with_2',
    'post_status',
    'wp_posts',
    'with_1'
);

craigfrancis avatar Aug 16 '22 10:08 craigfrancis