wpdb::delete()publicWP 3.4.0

Deletes rows from the table based on the condition specified in the $where parameter.

Enables protection against SQL injections, which means that uncleaned data can be passed, for example: $_GET['foo']...

Method of the class: wpdb{}

No Hooks.

Returns

Int|false. The number of deleted rows or 0 if nothing was deleted. false is returned on query error.

Usage

global $wpdb;
$wpdb->delete( $table, $where, $where_format );
$table(string) (required)
The name of the table.
$where(array) (required)
An array of conditions that will be used to select rows for deletion in the format [ 'column name' => 'value' ]. Multiple conditions will be combined using AND. If the value is set to NULL, the query will perform a comparison IS NULL, and the corresponding format will be ignored.
$where_format(array/string)

An array of data formats that will be associated with the specified values in the $where parameter. If a string is provided, it (the format) will be associated with all data. When a format is specified, WordPress converts the provided data to the specified format before creating the query. Possible formats:

  • %s - string
  • %d - integer
  • %f - float

If not specified, the format string will be used for all values of $data, unless otherwise specified in the wpdb::$field_types.
Default: null

Examples

3

#1 Example of deleting data from the database

// Delete row with field ID=1 from table table
$wpdb->delete( 'table', [ 'ID' => 1 ] );

// Let's specify the format of the value $where
$wpdb->delete( 'table', [ 'ID'=>'1' ], [ '%d' ] ); // 1 will be treated as (int) (%d).
0

#2 Multiple "where" and "type"

$where = [
	'UID'  => 248,
	'File' => "C:\file.txt"
];

$where_format = [
	'%d',
	'%s'
];

$wpdb->delete( $table, $where, $where_format );

Notes

Changelog

Since 3.4.0 Introduced.

wpdb::delete() code WP 6.9

public function delete( $table, $where, $where_format = null ) {
	if ( ! is_array( $where ) ) {
		return false;
	}

	$where = $this->process_fields( $table, $where, $where_format );
	if ( false === $where ) {
		return false;
	}

	$conditions = array();
	$values     = array();
	foreach ( $where as $field => $value ) {
		if ( is_null( $value['value'] ) ) {
			$conditions[] = "`$field` IS NULL";
			continue;
		}

		$conditions[] = "`$field` = " . $value['format'];
		$values[]     = $value['value'];
	}

	$conditions = implode( ' AND ', $conditions );

	$sql = "DELETE FROM `$table` WHERE $conditions";

	$this->check_current_query = false;
	return $this->query( $this->prepare( $sql, $values ) );
}