wppaste
WordPress

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
Prepares a SQL query for safe execution.

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

Touches nothing outside its own arguments.

Scaling
Scales with input

The body loops, so the work grows with what you pass in.

Instructions
5–116

Executed per call on PHP 8.5, depending on the branch taken. The body compiles to 337.

Plugin surface
None

Nothing here hands control to plugin code.

Called by
5

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 inputpreg_split()called directly
  • hookthird-party callbacksdo_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.

WhenInstructionsCalls it makes
$query === null5none
$query !== null && !$key && $args_count === false65–73preg_split(), array_intersect(), vsprintf(), ->add_placeholder_escape()
$query !== null && !$key && $args_count !== false && $placeholder_count === 167–74preg_split(), array_intersect(), wp_load_translations_early(), __(), _doing_it_wrong()
$query !== null && !$key75–90preg_split(), array_intersect(), wp_load_translations_early(), __(), sprintf(), _doing_it_wrong()
$query !== null && !$key && $args_count === false79–87wp_load_translations_early(), __(), sprintf(), _doing_it_wrong(), preg_split(), array_intersect(), vsprintf(), ->add_placeholder_escape()
$query !== null && !$key && $args_count !== false && $placeholder_count === 181–88wp_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_count84–102preg_split(), array_intersect(), wp_load_translations_early(), __(), sprintf(), _doing_it_wrong(), vsprintf(), ->add_placeholder_escape()
$query !== null && !$key89–104wp_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_count98–116wp_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

PHPCompiledExecutedBranchesNotes
8.6-dev3375–11641
8.53375–11641
8.43375–1164157 fewer instructions than PHP 8.3
8.33945–12841
8.23945–12841
8.13945–128412 fewer instructions than PHP 7.4
7.43965–12841

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

Used by · 5

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.

  1. 6.7.7
  2. 6.8.8
  3. 6.9.7
  4. 7.0.4
  5. 7.1.0

Signature, return type and hooks compared across 5 parsed releases.

7.1.0
Return type changed from string|void to string|null.verified against source
6.2.0
Added %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
5.3.0
Formalized the existing and already documented ...$args parameter by updating the function signature. The second parameter was changed from $args to ...$args.from the docblock
2.3.0
Introduced.from the docblock

About 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.