On this page
wpdb::prepare( string $query, mixed $args ): string|void
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)
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'
);
Parameters
$querystring Required-
Query statement with sprintf()-like placeholders.
$argsmixed Required-
Further variables to substitute into the query's placeholders if being called with individual arguments.
Return
string|void Sanitized query string, if there is a query to prepare.
Source
File: wp-includes/class-wpdb.php. View all references
public function prepare( $query, ...$args ) {
if ( is_null( $query ) ) {
return;
}
// This is not meant to be foolproof -- but it will catch obviously incorrect usage.
if ( strpos( $query, '%' ) === false ) {
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'
);
}
// If args were passed as an array (as in vsprintf), move them up.
$passed_as_array = false;
if ( isset( $args[0] ) && is_array( $args[0] ) && 1 === count( $args ) ) {
$passed_as_array = true;
$args = $args[0];
}
foreach ( $args as $arg ) {
if ( ! is_scalar( $arg ) && ! is_null( $arg ) ) {
wp_load_translations_early();
_doing_it_wrong(
'wpdb::prepare',
sprintf(
/* translators: %s: Value type. */
__( 'Unsupported value type (%s).' ),
gettype( $arg )
),
'4.8.2'
);
}
}
/*
* 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.
$query = preg_replace( '/(?<!%)%s/', "'%s'", $query ); // Quote the strings, avoiding escaped strings like %%s.
$query = preg_replace( "/(?<!%)(%($allowed_format)?f)/", '%\\2F', $query ); // Force floats to be locale-unaware.
$query = preg_replace( "/%(?:%|$|(?!($allowed_format)?[sdF]))/", '%%\\1', $query ); // Escape any unescaped percents.
// Count the number of valid placeholders in the query.
$placeholders = preg_match_all( "/(^|[^%]|(%%)+)%($allowed_format)?[sdF]/", $query, $matches );
$args_count = count( $args );
if ( $args_count !== $placeholders ) {
if ( 1 === $placeholders && $passed_as_array ) {
// If the passed query only expected one argument, but the wrong number of arguments were sent as an array, bail.
wp_load_translations_early();
_doing_it_wrong(
'wpdb::prepare',
__( 'The query only expected one placeholder, but an array of multiple placeholders was sent.' ),
'4.9.0'
);
return;
} else {
/*
* If we don't have the right number of placeholders,
* but they were passed as individual arguments,
* or we were expecting multiple arguments in an array, throw a warning.
*/
wp_load_translations_early();
_doing_it_wrong(
'wpdb::prepare',
sprintf(
/* translators: 1: Number of placeholders, 2: Number of arguments passed. */
__( 'The query does not contain the correct number of placeholders (%1$d) for the number of arguments passed (%2$d).' ),
$placeholders,
$args_count
),
'4.8.3'
);
/*
* If we don't have enough arguments to match the placeholders,
* return an empty string to avoid a fatal error on PHP 8.
*/
if ( $args_count < $placeholders ) {
$max_numbered_placeholder = ! empty( $matches[3] ) ? max( array_map( 'intval', $matches[3] ) ) : 0;
if ( ! $max_numbered_placeholder || $args_count < $max_numbered_placeholder ) {
return '';
}
}
}
}
array_walk( $args, array( $this, 'escape_by_ref' ) );
$query = vsprintf( $query, $args );
return $this->add_placeholder_escape( $query );
}
Related
Uses
| Uses | Description |
|---|---|
| wpdb::add_placeholder_escape() wp-includes/class-wpdb.php | Adds a placeholder escape string, to escape anything that resembles a printf() placeholder. |
| wp_load_translations_early() wp-includes/load.php | Attempt an early load of translations. |
| __() wp-includes/l10n.php | Retrieves the translation of $text. |
| _doing_it_wrong() wp-includes/functions.php | Marks something as being incorrectly called. |
Used By
| Used By | Description |
|---|---|
| WP_Site_Health::should_suggest_persistent_object_cache() wp-admin/includes/class-wp-site-health.php | Determines whether to suggest using a persistent object cache. |
| WP_Debug_Data::get_mysql_var() wp-admin/includes/class-wp-debug-data.php | Returns the value of a MySQL system variable. |
| _wp_batch_update_comment_type() wp-includes/comment.php | Updates the comment type for a batch of comments. |
| wp_delete_site() wp-includes/ms-site.php | Deletes a site from the database. |
| populate_network_meta() wp-admin/includes/schema.php | Creates WordPress network meta and sets the default values. |
| populate_site_meta() wp-admin/includes/schema.php | Creates WordPress site meta and sets the default values. |
| _find_post_by_old_slug() wp-includes/query.php | Find the post ID for redirecting an old slug. |
| _find_post_by_old_date() wp-includes/query.php | Find the post ID for redirecting an old date. |
| wp_delete_attachment_files() wp-includes/post.php | Deletes all files that belong to the given attachment. |
| WP_Privacy_Requests_Table::get_request_counts() wp-admin/includes/class-wp-privacy-requests-table.php | Count number of requests for each status. |
| has_term_meta() wp-includes/taxonomy.php | Gets all meta data, including meta IDs, for the given term ID. |
| delete_expired_transients() wp-includes/option.php | Deletes all expired transients. |
| wp_check_comment_flood() wp-includes/comment.php | Checks whether comment flooding is occurring. |
| WP_Term_Query::get_search_sql() wp-includes/class-wp-term-query.php | Used internally to generate a SQL string related to the ‘search’ parameter. |
| WP_Term_Query::get_terms() wp-includes/class-wp-term-query.php | Retrieves the query results. |
| WP_Network_Query::get_search_sql() wp-includes/class-wp-network-query.php | Used internally to generate an SQL string for searching across multiple columns. |
| WP_Network_Query::get_network_ids() wp-includes/class-wp-network-query.php | Used internally to get a list of network IDs matching the query vars. |
| WP_Site_Query::get_search_sql() wp-includes/class-wp-site-query.php | Used internally to generate an SQL string for searching across multiple columns. |
| WP_Site_Query::get_site_ids() wp-includes/class-wp-site-query.php | Used internally to get a list of site IDs matching the query vars. |
| wxr_term_meta() wp-admin/includes/export.php | Outputs term meta XML tags for a given term object. |
| WP_Site::get_instance() wp-includes/class-wp-site.php | Retrieves a site from the database by its ID. |
| WP_Upgrader::create_lock() wp-admin/includes/class-wp-upgrader.php | Creates a lock using WordPress options. |
| WP_Network::get_instance() wp-includes/class-wp-network.php | Retrieves a network from the database by its ID. |
| wp_term_is_shared() wp-includes/taxonomy.php | Determines whether a term is shared between multiple taxonomies. |
| WP_Comment::get_instance() wp-includes/class-wp-comment.php | Retrieves a WP_Comment instance. |
| wp_get_users_with_no_role() wp-includes/user.php | Gets the user IDs of all users with no role on this site. |
| WP_Comment_Query::get_comment_ids() wp-includes/class-wp-comment-query.php | Used internally to get a list of comment IDs matching the query vars. |
| WP_Term::get_instance() wp-includes/class-wp-term.php | Retrieve WP_Term instance. |
| delete_network_option() wp-includes/option.php | Removes a network option by name. |
| get_network_option() wp-includes/option.php | Retrieves a network’s option value based on the option name. |
| _wp_batch_split_terms() wp-includes/taxonomy.php | Splits a batch of shared taxonomy terms. |
| wpdb::strip_invalid_text() wp-includes/class-wpdb.php | Strips any invalid characters based on value/charset pairs. |
| wp_media_attach_action() wp-admin/includes/media.php | Encapsulates the logic for Attach/Detach actions. |
| WP_Meta_Query::get_sql_for_clause() wp-includes/class-wp-meta-query.php | Generate SQL JOIN and WHERE clauses for a first-order query clause. |
| WP_Tax_Query::get_sql_for_clause() wp-includes/class-wp-tax-query.php | Generates SQL JOIN and WHERE clauses for a “first-order” query clause. |
| WP_Date_Query::get_sql_for_clause() wp-includes/class-wp-date-query.php | Turns a first-order date query into SQL for a WHERE clause. |
| attachment_url_to_postid() wp-includes/media.php | Tries to convert an attachment URL into a post ID. |
| display_setup_form() wp-admin/install.php | Displays installer setup form. |
| network_domain_check() wp-admin/includes/network.php | Check for an existing network. |
| export_date_options() wp-admin/export.php | Create the date options fields for exporting a given post type. |
| export_wp() wp-admin/includes/export.php | Generates the WXR export file for download. |
| WP_User_Search::prepare_query() wp-admin/includes/deprecated.php | Prepares the user search query (legacy). |
| get_author_user_ids() wp-admin/includes/deprecated.php | Get all user IDs. |
| get_editable_user_ids() wp-admin/includes/deprecated.php | Gets the IDs of any users who can edit posts. |
| get_nonauthor_user_ids() wp-admin/includes/deprecated.php | Gets all users who are not authors. |
| get_others_unpublished_posts() wp-admin/includes/deprecated.php | Retrieves editable posts from other users. |
| WP_List_Table::months_dropdown() wp-admin/includes/class-wp-list-table.php | Displays a dropdown for filtering items in the list table by month. |
| wpmu_delete_user() wp-admin/includes/ms.php | Delete a user from the network and remove from all sites. |
| populate_network() wp-admin/includes/schema.php | Populate network settings. |
| populate_options() wp-admin/includes/schema.php | Create WordPress options and set the default values. |
| maybe_create_table() wp-admin/includes/upgrade.php | Creates a table in the database, if it doesn’t already exist. |
| wp_install_defaults() wp-admin/includes/upgrade.php | Creates the initial content for a newly-installed site. |
| get_users_drafts() wp-admin/includes/user.php | Retrieve the user’s drafts. |
| wp_delete_user() wp-admin/includes/user.php | Remove user and optionally reassign posts and links to another user. |
| meta_form() wp-admin/includes/template.php | Prints the form in the Custom Fields meta box. |
| parent_dropdown() wp-admin/includes/template.php | Prints out option HTML elements for the page parents drop-down. |
| WP_MS_Sites_List_Table::prepare_items() wp-admin/includes/class-wp-ms-sites-list-table.php | Prepares the list of sites for display. |
| update_gallery_tab() wp-admin/includes/media.php | Adds the gallery tab back to the tabs array if post has image attachments. |
| has_meta() wp-admin/includes/post.php | Returns meta data for the given post ID. |
| get_available_post_mime_types() wp-includes/post.php | Gets all available post MIME types for a given post type. |
| post_exists() wp-admin/includes/post.php | Determines if a post exists based on title, content, date and type. |
| WP_Importer::get_imported_comments() wp-admin/includes/class-wp-importer.php | Set array with imported comments from WordPress database |
| WP_Importer::get_imported_posts() wp-admin/includes/class-wp-importer.php | Returns array with imported permalinks from WordPress database |
| WP_Importer::count_imported_posts() wp-admin/includes/class-wp-importer.php | Return count of imported permalinks from WordPress database |
| _wp_delete_orphaned_draft_menu_items() wp-admin/includes/nav-menu.php | Deletes orphaned draft menu items |
| comment_exists() wp-admin/includes/comment.php | Determines if a comment exists based on author and date. |
| WP_Posts_List_Table::__construct() wp-admin/includes/class-wp-posts-list-table.php | Constructor. |
| WP_User::get_data_by() wp-includes/class-wp-user.php | Returns only the main user fields. |
| wp_get_archives() wp-includes/general-template.php | Displays archive links based on type and format. |
| delete_usermeta() wp-includes/deprecated.php | Remove user meta data. |
| get_usermeta() wp-includes/deprecated.php | Retrieve user metadata. |
| update_usermeta() wp-includes/deprecated.php | Update metadata of user. |
| WP_Query::get_posts() wp-includes/class-wp-query.php | Retrieves an array of posts based on query variables. |
| WP_Query::parse_search() wp-includes/class-wp-query.php | Generates SQL for the WHERE clause based on passed search terms. |
| WP_Query::parse_search_order() wp-includes/class-wp-query.php | Generates SQL for the ORDER BY condition based on passed search terms. |
| wp_scheduled_delete() wp-includes/functions.php | Permanently deletes comments or posts of any type that have held a status of ‘trash’ for the number of days defined in EMPTY_TRASH_DAYS. |
| do_enclose() wp-includes/functions.php | Checks content for video and audio links to add as enclosures. |
| _update_post_term_count() wp-includes/taxonomy.php | Updates term count based on object types of the current taxonomy. |
| _update_generic_term_count() wp-includes/taxonomy.php | Updates term count based on number of objects. |
| wp_unique_term_slug() wp-includes/taxonomy.php | Makes term slug unique, if it isn’t already. |
| wp_update_term() wp-includes/taxonomy.php | Updates term based on arguments provided. |
| wp_set_object_terms() wp-includes/taxonomy.php | Creates term and taxonomy relationships. |
| wp_insert_term() wp-includes/taxonomy.php | Adds a new term to the database. |
| wp_remove_object_terms() wp-includes/taxonomy.php | Removes term(s) associated with a given object. |
| wp_delete_term() wp-includes/taxonomy.php | Removes a term from the database. |
| get_adjacent_post() wp-includes/link-template.php | Retrieves the adjacent post. |
| ms_allowed_http_request_hosts() wp-includes/http.php | Adds any domain in a multisite installation for safe HTTP requests to the allowed list. |
| WP_Date_Query::build_time_query() wp-includes/class-wp-date-query.php | Builds a query string for comparing time values (hour, minute, second). |
| wp_load_core_site_options() wp-includes/option.php | Loads and caches certain often requested site options if is_multisite() and a persistent cache is not being used. |
| add_option() wp-includes/option.php | Adds a new option. |
| delete_option() wp-includes/option.php | Removes option by name. Prevents removal of protected WordPress options. |
| get_option() wp-includes/option.php | Retrieves an option value based on an option name. |
| WP_User_Query::prepare_query() wp-includes/class-wp-user-query.php | Prepares the query variables. |
| WP_User_Query::get_search_sql() wp-includes/class-wp-user-query.php | Used internally to generate an SQL string for searching across multiple columns. |
| wp_insert_user() wp-includes/user.php | Inserts a user into the database. |
| count_users() wp-includes/user.php | Counts number of users who have each of the user roles. |
| wp_enqueue_media() wp-includes/media.php | Enqueues all scripts, styles, settings, and templates necessary to use all media JS APIs. |
| WP_Post::get_instance() wp-includes/class-wp-post.php | Retrieve WP_Post instance. |
| get_posts_by_author_sql() wp-includes/post.php | Retrieves the post SQL based on capability, author, and type. |
| wp_delete_attachment() wp-includes/post.php | Trashes or deletes an attachment. |
| get_pages() wp-includes/post.php | Retrieves an array of pages (or hierarchical post type items). |
| wp_unique_post_slug() wp-includes/post.php | Computes a unique slug for the post, when given the desired slug and some post details. |
| wp_untrash_post_comments() wp-includes/post.php | Restores comments for a post from the Trash. |
| wp_insert_post() wp-includes/post.php | Inserts or update a post. |
| wp_delete_post() wp-includes/post.php | Trashes or deletes a post or page. |
| wp_trash_post_comments() wp-includes/post.php | Moves comments for a post to the Trash. |
| wp_count_posts() wp-includes/post.php | Counts number of posts of a post type and if user has permissions to view. |
| WP_Rewrite::page_uri_index() wp-includes/class-wp-rewrite.php | Retrieves all pages and attachments for pages URIs. |
| redirect_canonical() wp-includes/canonical.php | Redirects incoming links to the proper URL based on the site url. |
| redirect_guess_404_permalink() wp-includes/canonical.php | Attempts to guess the correct URL for a 404 request based on query vars. |
| _wp_upgrade_revisions_of_post() wp-includes/revision.php | Upgrades the revisions author, adds the current post as a revision and sets the revisions version to 1. |
| wp_get_post_autosave() wp-includes/revision.php | Retrieves the autosaved data of the specified post. |
| get_most_recent_post_of_user() wp-includes/ms-functions.php | Gets a user’s most recent post. |
| wpmu_activate_signup() wp-includes/ms-functions.php | Activates a signup. |
| wpmu_validate_user_signup() wp-includes/ms-functions.php | Sanitizes and validates data required for a user sign-up. |
| wpmu_validate_blog_signup() wp-includes/ms-functions.php | Processes new site registrations. |
| get_admin_users_for_domain() wp-includes/ms-deprecated.php | Get the admin for a domain/path combination. |
| remove_user_from_blog() wp-includes/ms-functions.php | Removes a user from a blog. |
| get_bookmark() wp-includes/bookmark.php | Retrieves bookmark data. |
| get_bookmarks() wp-includes/bookmark.php | Retrieves the list of bookmarks. |
| ms_not_installed() wp-includes/ms-load.php | Displays a failure message. |
| get_blog_list() wp-includes/ms-deprecated.php | Deprecated functionality to retrieve a list of all sites. |
| get_blog_status() wp-includes/ms-blogs.php | Get a blog details field. |
| get_last_updated() wp-includes/ms-blogs.php | Get a list of most recently updated blogs. |
| get_blog_details() wp-includes/ms-blogs.php | Retrieve the details for a blog from the blogs table and blog options. |
| wp_xmlrpc_server::mt_getTrackbackPings() wp-includes/class-wp-xmlrpc-server.php | Retrieve trackbacks sent to a given post. |
| wp_xmlrpc_server::pingback_ping() wp-includes/class-wp-xmlrpc-server.php | Retrieves a pingback and registers it. |
| wp_xmlrpc_server::pingback_extensions_getPingbacks() wp-includes/class-wp-xmlrpc-server.php | Retrieve array of URLs that pingbacked the given URL. |
| wpdb::_insert_replace_helper() wp-includes/class-wpdb.php | Helper function for insert and replace. |
| wpdb::update() wp-includes/class-wpdb.php | Updates a row in the table. |
| wpdb::delete() wp-includes/class-wpdb.php | Deletes a row in the table. |
| wpdb::set_charset() wp-includes/class-wpdb.php | Sets the connection’s character set. |
| trackback() wp-includes/comment.php | Sends a Trackback. |
| WP_Comment_Query::get_search_sql() wp-includes/class-wp-comment-query.php | Used internally to generate an SQL string for searching across multiple columns. |
| wp_update_comment_count_now() wp-includes/comment.php | Updates the comment count for the post. |
| do_trackbacks() wp-includes/comment.php | Performs trackbacks. |
| wp_delete_comment() wp-includes/comment.php | Trashes or deletes a comment. |
| get_lastcommentmodified() wp-includes/comment.php | Retrieves the date the last comment was modified. |
| wp_allow_comment() wp-includes/comment.php | Validates whether this comment is allowed to be made. |
| check_comment() wp-includes/comment.php | Checks whether a comment passes internal checks to be allowed to add. |
| delete_metadata() wp-includes/meta.php | Deletes metadata for the specified object. |
| get_metadata_by_mid() wp-includes/meta.php | Retrieves metadata by meta ID. |
| add_metadata() wp-includes/meta.php | Adds metadata for the specified object. |
| update_metadata() wp-includes/meta.php | Updates metadata for the specified object. If no value already exists for the specified object ID and metadata key, the metadata will be added. |
Changelog
© 2003–2022 WordPress Foundation
Licensed under the GNU GPLv2+ License.
https://developer.wordpress.org/reference/classes/wpdb/prepare