wpdb::prepare( string $query, array|mixed $args ): string|void
- Since
- 2.3.0, 5.3.0, 6.2.0
- Source
wp-includes/class-wpdb.php:1464
Description
Uses sprintf()-like syntax. The following placeholders can be used in the query string:
%d(integer)%f(float)%s(string)%i(identifier, e.g. table/field names)
All placeholders MUST be left unquoted in the query string. A corresponding argument MUST be passed for each placeholder.
Note: There is one exception to the above: for compatibility with old behavior, numbered or formatted string placeholders (eg, %1$s, %5s) will not have quotes added by this function, so should be passed with appropriate quotes around them.
Literal percentage signs (%) in the query string must be written as %%. Percentage wildcards (for example, to use in LIKE syntax) must be passed via a substitution argument containing the complete LIKE string, these cannot be inserted directly in the query string.
Also see wpdb::esc_like().
Arguments may be passed as individual arguments to the method, or as a single array containing all arguments. A combination of the two is not supported.
Examples:
$wpdb->prepare(
"SELECT * FROM table WHERE column = %s AND field = %d OR other_field LIKE %s",
array( 'foo', 1337, '%bar' )
);
$wpdb->prepare(
"SELECT DATE_FORMAT(field, '%%c') FROM table WHERE column = %s",
'foo'
);
$wpdb->prepare(
"SELECT * FROM %i WHERE %i = %s",
$table,
$field,
$value
);Compatibility
- WordPress
- since 6.2.0
- PHP
- 7.4–8.6-dev
- 6.7.7
- 6.8.8
- 6.9.7
- 7.0.4
- 7.1.0
Present in every tracked release (6.7.7 to 7.1.0), and compiles on PHP 7.4 through 8.6-dev.
Parameters
$querystring- Query statement with
sprintf()-like placeholders. $argsarray|mixed- The array of variables to substitute into the query's placeholders if being called with an array of arguments, or the first variable to substitute into the query's placeholders if being called with individual arguments.
Return value
string|void- Sanitized query string, if there is a query to prepare.
Performance profile
How much work a call to wpdb::prepare() does, and what it touches: the algorithmic scaling, the Zend instruction count per call across PHP versions, the hooks it hands control to, and the core code that calls it. Measured from the compiled opcodes, not a stopwatch, so every number is identical on any machine running the same PHP version, and every function in core is ranked by cost.
- Cost class
- Light
- Scaling
- Scales with input
- Instructions
- 5–116
- Plugin surface
- None
- Called by
- 5
Touches nothing outside its own arguments.
The body loops, so the work grows with what you pass in.
Executed per call on PHP 8.5, depending on the branch taken. The body compiles to 337.
Nothing here hands control to plugin code.
5 places in core call this, so the cost is paid more often than your own code shows.
What it touches
- regexregular expression over the whole input
preg_split()called directly - hookthird-party callbacks
do_action()one call below wpdb::prepare()
Further down the call graph this can also reach query, option, cache, serialize and transient. Those are the worst case, several calls deep and usually down an error path, not what a normal call pays.
What one call costs · 9 distinct outcomes
One number would be a lie: the work depends on which branch runs. These are every distinct cost wpdb::prepare() can have, taken from its control-flow graph on PHP 8.5.
| When | Instructions | Calls it makes |
|---|---|---|
$query === null | 5 | none |
$query !== null && !$key && $args_count === false | 65–73 | preg_split(), array_intersect(), vsprintf(), ->add_placeholder_escape() |
$query !== null && !$key && $args_count !== false && $placeholder_count === 1 | 67–74 | preg_split(), array_intersect(), wp_load_translations_early(), __(), _doing_it_wrong() |
$query !== null && !$key | 75–90 | preg_split(), array_intersect(), wp_load_translations_early(), __(), sprintf(), _doing_it_wrong() |
$query !== null && !$key && $args_count === false | 79–87 | wp_load_translations_early(), __(), sprintf(), _doing_it_wrong(), preg_split(), array_intersect(), vsprintf(), ->add_placeholder_escape() |
$query !== null && !$key && $args_count !== false && $placeholder_count === 1 | 81–88 | wp_load_translations_early(), __(), sprintf(), _doing_it_wrong(), preg_split(), array_intersect(), wp_load_translations_early(), __(), _doing_it_wrong() |
$query !== null && !$key && $args_count !== false && !$args_count | 84–102 | preg_split(), array_intersect(), wp_load_translations_early(), __(), sprintf(), _doing_it_wrong(), vsprintf(), ->add_placeholder_escape() |
$query !== null && !$key | 89–104 | wp_load_translations_early(), __(), sprintf(), _doing_it_wrong(), preg_split(), array_intersect(), wp_load_translations_early(), __(), sprintf(), _doing_it_wrong() |
$query !== null && !$key && $args_count !== false && !$args_count | 98–116 | wp_load_translations_early(), __(), sprintf(), _doing_it_wrong(), preg_split(), array_intersect(), wp_load_translations_early(), __(), sprintf(), _doing_it_wrong(), vsprintf(), ->add_placeholder_escape() |
Across PHP versions
| PHP | Compiled | Executed | Branches | Notes |
|---|---|---|---|---|
| 8.6-dev | 337 | 5–116 | 41 | |
| 8.5 | 337 | 5–116 | 41 | |
| 8.4 | 337 | 5–116 | 41 | 57 fewer instructions than PHP 8.3 |
| 8.3 | 394 | 5–128 | 41 | |
| 8.2 | 394 | 5–128 | 41 | |
| 8.1 | 394 | 5–128 | 41 | 2 fewer instructions than PHP 7.4 |
| 7.4 | 396 | 5–128 | 41 |
An instruction is not a fixed amount of time, so a matching count is not necessarily the same speed; what it rules out is a difference in the work itself.
Uses · 6
- wp_load_translations_early()Attempts an early load of translations.
- _doing_it_wrong()Marks something as being incorrectly called.
- __()Retrieves the translation of $text.
- wpdb::_escape_identifier_value()Escapes an identifier value without adding the surrounding quotes.
- wpdb::_real_escape()Real escape using mysqli_real_escape_string().
- wpdb::add_placeholder_escape()Adds a placeholder escape string, to escape anything that resembles a printf() placeholder.
Used by · 5
- wpdb::_insert_replace_helper()Helper function for insert and replace.
- wpdb::delete()Deletes a row in the table.
- wpdb::set_charset()Sets the connection's character set.
- wpdb::strip_invalid_text()Strips any invalid characters based on value/charset pairs.
- wpdb::update()Updates a row in the table.
Source code
public function prepare( $query, ...$args ) { if ( is_null( $query ) ) { return; } /* * This is not meant to be foolproof -- but it will catch obviously incorrect usage. * * Note: str_contains() is not used here, as this file can be included * directly outside of WordPress core, e.g. by HyperDB, in which case * the polyfills from wp-includes/compat.php are not loaded. */ if ( false === strpos( $query, '%' ) ) { wp_load_translations_early(); _doing_it_wrong( 'wpdb::prepare', sprintf( /* translators: %s: wpdb::prepare() */ __( 'The query argument of %s must have a placeholder.' ), 'wpdb::prepare()' ), '3.9.0' ); } /* * Specify the formatting allowed in a placeholder. The following are allowed: * * - Sign specifier, e.g. $+d * - Numbered placeholders, e.g. %1$s * - Padding specifier, including custom padding characters, e.g. %05s, %'#5s * - Alignment specifier, e.g. %05-s * - Precision specifier, e.g. %.2f */ $allowed_format = '(?:[1-9][0-9]*[$])?[-+0-9]*(?: |0|\'.)?[-+0-9]*(?:\.[0-9]+)?'; /* * If a %s placeholder already has quotes around it, removing the existing quotes * and re-inserting them ensures the quotes are consistent. * * For backward compatibility, this is only applied to %s, and not to placeholders like %1$s, * which are frequently used in the middle of longer strings, or as table name placeholders. */ $query = str_replace( "'%s'", '%s', $query ); // Strip any existing single quotes. $query = str_replace( '"%s"', '%s', $query ); // Strip any existing double quotes. // Escape any unescaped percents (i.e. anything unrecognised). $query = preg_replace( "/%(?:%|$|(?!($allowed_format)?[sdfFi]))/", '%%\\1', $query ); // Extract placeholders from the query. $split_query = preg_split( "/(^|[^%]|(?:%%)+)(%(?:$allowed_format)?[sdfFi])/", $query, -1, PREG_SPLIT_DELIM_CAPTURE ); $split_query_count = count( $split_query ); /* * Split always returns with 1 value before the first placeholder (even with $query = "%s"), * then 3 additional values per placeholder. */ $placeholder_count = ( ( $split_query_count - 1 ) / 3 ); // If args were passed as an array, as in vsprintf(), move them up. $passed_as_array = ( isset( $args[0] ) && is_array( $args[0] ) && 1 === count( $args ) ); if ( $passed_as_array ) { $args = $args[0]; } $new_query = ''; $key = 2; // Keys 0 and 1 in $split_query contain values before the first placeholder. $arg_id = 0; $arg_identifiers = array(); $arg_strings = array(); while ( $key < $split_query_count ) { $placeholder = $split_query[ $key ]; $format = substr( $placeholder, 1, -1 ); $type = substr( $placeholder, -1 ); if ( 'f' === $type && true === $this->allow_unsafe_unquoted_parameters /*Changelog
Introduced in 2.3.0. One change between 6.7.7 and 7.1.0.
Signature, return type and hooks compared across 5 parsed releases.
string|void to string|null.verified against source%i for identifiers, e.g. table or field names.Check support via
wpdb::has_cap( 'identifier_placeholders' ).This preserves compatibility with
sprintf(), as the C version uses %d and $i as a signed integer, whereas PHP only supports %d.from the docblock...$args parameter by updating the function signature. The second parameter was changed from $args to ...$args.from the docblockAbout this page
- Parsed data
- Generated from the wordpress-develop 6.9.7 tag, from
src/wp-includes/class-wpdb.php, and regenerated for each WordPress release so it tracks the code rather than a snapshot of it. - Corrections
- Something wrong on this page? Report it and it gets fixed in the next regeneration.