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: leave placeholders unquoted in the SQL template, escape identifiers with %i, and wrap LIKE wildcards via esc_like().
Summary
- Every dynamic SQL query using
$wpdbshould pass throughwpdb::prepare(), which formats and escapes values usingsprintf()-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
%sor%iin quotes inside the query template—wpdb::prepare()adds the proper quoting automatically. - For
LIKEqueries, escape user input with$wpdb->esc_like()first, append%wildcards in PHP, and pass the complete pattern to a%splaceholder.
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
- Back up your database and test on staging. Before refactoring custom plugin queries, verify your restore workflow with a WordPress backup restore rehearsal.
- Search custom themes and plugins for
$wpdb->. Grep forget_results,get_var,get_row,get_col, andqueryacrosswp-content/themes/andwp-content/plugins/. - Verify every dynamic query uses
prepare(). Any call that concatenates$_GET,$_POST, or even internal variables directly into SQL should be converted towpdb::prepare()with%i,%s,%d, or%f. - Check
IN (...)clauses. WordPressprepare()does not expand a PHP array into a single%splaceholder. Build the placeholder string dynamically fromcount( $ids )(implode( ',', array_fill( 0, count( $ids ), '%d' ) )) and pass the array as the argument list. - Pair query safety with query performance. If you only need standard posts, prefer
WP_Querywithno_found_rows => truefor non-paginated loops, and audit heavy options using WordPresswp_optionsautoloaded cleanup.
Common mistakes
- Passing raw
$_POSTarrays directly as the second argument toprepare( $sql, $args ). As the officialwpdbdocs warn, allowing untrusted user input directly as thevsprintf-style$argsarray lets an attacker manipulate placeholder substitution. Validate and pass explicit arguments. - Wrapping
%sor%iin quotes ('%s'). Only legacy numbered placeholders like%1$slacked auto-quoting; standard unnumbered placeholders must stay unquoted. - Interpolating dynamic
ORDER BYcolumn names from query parameters. Even with%i, always check$orderbyagainst a strict allowlist of known column names before passing it to SQL. - Using
$wpdbwhenWP_Queryorget_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.