How to Use wpdb::prepare() and %i Identifier Placeholders Safely in WordPress

Whenever a WordPress plugin queries a custom database table or runs reporting SQL that WP_Query cannot express cleanly, you end up using the global $wpdb object. The catch is that $wpdb->get_results() and $wpdb->query() execute raw SQL strings—meaning one interpolated variable opens a SQL injection flaw. Using $wpdb->prepare() correctly (including %i for table and column names and $wpdb->esc_like() for wildcard searches) keeps custom database code safe and clean.

Editorial illustration of WordPress wpdb::prepare() placeholder rules for values and identifiers

Editorial illustration: leave placeholders unquoted in the SQL template, escape identifiers with %i, and wrap LIKE wildcards via esc_like().

Summary

  • Every dynamic SQL query using $wpdb should pass through wpdb::prepare(), which formats and escapes values using sprintf()-style placeholders (%d, %f, %s, and %i).
  • Use %i (introduced in WordPress 6.2) when substituting table names or column identifiers dynamically instead of interpolating $wpdb->prefix . 'my_table' directly into SQL strings.
  • Never wrap %s or %i in quotes inside the query template—wpdb::prepare() adds the proper quoting automatically.
  • For LIKE queries, escape user input with $wpdb->esc_like() first, append % wildcards in PHP, and pass the complete pattern to a %s placeholder.

How wpdb::prepare() placeholders work

Per the WordPress Developer Reference for wpdb::prepare(), the method accepts a SQL query template followed by one argument per placeholder (or a single array of arguments):

  • %d: Integer value
  • %f: Floating-point value
  • %s: String value
  • %i: Identifier (such as a table name or column name)

Here is a clean example querying a custom plugin table:

global $wpdb;

$table_name = $wpdb->prefix . 'event_logs';
$status     = 'failed';
$limit      = 25;

$sql = $wpdb->prepare(
    'SELECT id, created_at, message FROM %i WHERE status = %s ORDER BY id DESC LIMIT %d',
    $table_name,
    $status,
    $limit
);

$rows = $wpdb->get_results( $sql );

Notice there are no quotes around %i or %s. wpdb::prepare() quotes string values with single quotes and escapes identifiers appropriately (backticks). Putting '%s' inside your SQL string causes double-quoting or malformed queries.

Handling LIKE searches properly

A classic WordPress bug happens when developers write LIKE '%%%s%%' inside prepare(). As WordPress’s wpdb::prepare() documentation specifies, literal % signs must be handled cleanly, and wildcard patterns for LIKE must be built in PHP using $wpdb->esc_like():

global $wpdb;

$search  = sanitize_text_field( wp_unslash( $_GET['q'] ?? '' ) );
$pattern = '%' . $wpdb->esc_like( $search ) . '%';

$results = $wpdb->get_results(
    $wpdb->prepare(
        'SELECT id, title FROM %i WHERE title LIKE %s LIMIT 20',
        $wpdb->prefix . 'custom_items',
        $pattern
    )
);

Without $wpdb->esc_like(), a user searching for 100% or _admin introduces unintended SQL wildcards (% and _) that can degrade query performance on large tables.

When to use wpdb::insert() / wpdb::update() instead

For straightforward single-row writes, wpdb provides helper methods like $wpdb->insert(), $wpdb->update(), and $wpdb->delete() that handle formatting automatically:

$wpdb->insert(
    $wpdb->prefix . 'event_logs',
    array(
        'status'  => 'ok',
        'message' => $message,
    ),
    array( '%s', '%s' )
);

Keep both column names and values unescaped when passing them to $wpdb->insert(), and make sure all values are scalar (never arrays or objects).

Step-by-step: Audit existing $wpdb calls in your site

  1. Back up your database and test on staging. Before refactoring custom plugin queries, verify your restore workflow with a WordPress backup restore rehearsal.
  2. Search custom themes and plugins for $wpdb->. Grep for get_results, get_var, get_row, get_col, and query across wp-content/themes/ and wp-content/plugins/.
  3. Verify every dynamic query uses prepare(). Any call that concatenates $_GET, $_POST, or even internal variables directly into SQL should be converted to wpdb::prepare() with %i, %s, %d, or %f.
  4. Check IN (...) clauses. WordPress prepare() does not expand a PHP array into a single %s placeholder. Build the placeholder string dynamically from count( $ids ) (implode( ',', array_fill( 0, count( $ids ), '%d' ) )) and pass the array as the argument list.
  5. Pair query safety with query performance. If you only need standard posts, prefer WP_Query with no_found_rows => true for non-paginated loops, and audit heavy options using WordPress wp_options autoloaded cleanup.

Common mistakes

  • Passing raw $_POST arrays directly as the second argument to prepare( $sql, $args ). As the official wpdb docs warn, allowing untrusted user input directly as the vsprintf-style $args array lets an attacker manipulate placeholder substitution. Validate and pass explicit arguments.
  • Wrapping %s or %i in quotes ('%s'). Only legacy numbered placeholders like %1$s lacked auto-quoting; standard unnumbered placeholders must stay unquoted.
  • Interpolating dynamic ORDER BY column names from query parameters. Even with %i, always check $orderby against a strict allowlist of known column names before passing it to SQL.
  • Using $wpdb when WP_Query or get_terms() already works. Core APIs include built-in caching, filters, and sanitization that raw SQL bypasses.

Why this matters

SQL injection remains one of the highest-impact vulnerabilities in custom WordPress plugins because a single unescaped query can expose wp_users hashes or let attackers write admin accounts. Adopting wpdb::prepare() consistently—including %i for identifiers and esc_like() for searches—eliminates an entire class of plugin bugs.

My Take

Treat any $wpdb->get_results() or $wpdb->query() call that does not wrap a wpdb::prepare() call as a code-review blocker. Even for “trusted” internal table names or admin-only screens, using %i and %s consistently makes security audits and PHPCS checks effortless.

Conclusion

Pass all custom $wpdb SQL statements through wpdb::prepare(), use unquoted %s, %d, %f, and %i placeholders, build LIKE patterns with $wpdb->esc_like(), and validate dynamic ORDER BY columns against an allowlist.

Sources