wpdb::query()
Executes any queries to the WordPress database.
This method implies executing all queries except SELECT. For SELECT, there are special methods: $wpdb->get_results, $wpdb->get_row, $wpdb->get_col, $wpdb->get_var.
Keep in mind that, as with all functions of the wpdb class, the parameters passed need to be sanitized from SQL injections, which can be done in two ways:
// method 1 esc_sql( $user_entered_data_string ) // method 2 $wpdb->prepare( 'query' , value_parameter[, value_parameter ... ] )
Read more in the section "Protecting queries from SQL injections"
Method of the class: wpdb{}
Hooks from the method
Returns
Int|true|false.
true— for queries CREATE, ALTER, TRUNCATE, DROP.Number— of affected rows, for queries:DELETE/UPDATE/SELECT.false— when the query caused an error.
Usage
global $wpdb; $wpdb->query( $query );
- $query(string) (required)
- Database query.
Examples
#1 Remove the custom 'gargle' field and its value in post 13
$wpdb->query( "DELETE FROM $wpdb->postmeta WHERE post_id = 13 AND meta_key = 'gargle'" );
#2 Set parent page 7 for page 15
$wpdb->query( "UPDATE $wpdb->posts SET post_parent = 7 WHERE ID = 15 AND post_status = 'static'" );
#3 Delete orphaned custom fields
$wpdb->query( " DELETE pm FROM $wpdb->postmeta pm LEFT JOIN wp_posts wp ON wp.ID = pm.post_id WHERE wp.ID IS NULL " );
#4 Change the key of ACF repeater fields
$wpdb->query( " UPDATE $wpdb->postmeta SET meta_key = REPLACE(meta_key, 'knowledge-base-type', 'knowledge-base-list') WHERE `meta_key` LIKE '%knowledge-base-type%' " );
#5 Example using prepared statements
It is IMPORTANT to always use $wpdb->prepare() method when build your custom query:
$wpdb->query( $wpdb->prepare( "DELETE FROM $wpdb->postmeta WHERE post_id = %d AND meta_key = %s", 13, 'gargle' ) );
#6 Note about Return value for INSERT / DELETE / UPDATE / REPLACE requests
Be aware that because of the following check exists inside this function:
preg_match( '/^\s*(insert|delete|update|replace)\s/i', $query )
You may be surprised to not receive the expected $wpdb->rows_affected (and will miss the $wpdb->insert_id too) if you have anything except white-space characters before the UPDATE/INSERT/etc. statement, e.g.:
$rows_affected = $wpdb->query( " # this comment breaks the $return_val UPDATE wp_postmeta SET meta_value = 'baz' WHERE meta_key = 'foo' AND meta_value = 'bar' " ); echo $rows_affected; // will output 0 (actually $num_rows)
This will not work as expected – it will update your records but won’t return any value.
Changelog
| Since 0.71 | Introduced. |