wpdb::query()
Performs a MySQL database query, using current database connection.
More information can be found on the documentation page.
Method of the class: wpdb{}
Hooks from the method
Return
Int|true|false
. Boolean true for CREATE, ALTER, TRUNCATE and DROP queries. Number of rows affected/selected for all other queries. Boolean false on 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. |