WordPress.org

Codex

Attention Interested in functions, hooks, classes, or methods? Check out the new WordPress Code Reference!

Class Reference/wpdb/esc like

wpdb::esc_like() is a member of The wpdb Class.

Description

Sanitizes $text for use in a LIKE expression of an SQL query.

Note that the string still needs to be SQL escaped with $wpdb->prepare() or esc_sql(). This needs to be done after using $wpdb->esc_like(), to ensure correct and secure slashing of the string.

Usage

 <?php $like $wpdb->esc_like$text ); ?> 

Parameters

$text
(string) (required) The LIKE argument portion of the SQL query.
Default: None

Return Value

(string) 
Escaped value appropriate as a LIKE argument in a SQL query.

Example

Try to match a suspicious link to links in comments marked as spam.

// Parse a suspicious URL so we can just get the main parts.
$url = parse_url( $suspicious_link );

// Strip out "http://" and any url parameters.
if ( isset( $url['path'] ) ) {
	$link = $url['host'] . $url['path'];
} else {
	$link = $url['host'];
}

global $wpdb;

// First, escape the link for use in a LIKE statement.
$link = $wpdb->esc_like( $link );

// Add wildcards, since we are searching within comment text.
$link = '%' . $link . '%';

// Create a SQL statement with placeholders for the string input.
$sql = 	"
	SELECT COUNT(*)
	FROM $wpdb->comments 
	WHERE (comment_content LIKE %s OR comment_author_url LIKE %s)
		AND comment_approved = 'spam' 
	";

// Prepare the SQL statement so the string input gets escaped for security.
$sql = $wpdb->prepare( $sql, $link, $link );

// Search local spam for comments or author url containing this link.
$matching_comments = $wpdb->get_var( $sql );

echo $matching_comments . ' spam comments found with this link.';

Notes

Escapes % (percent) and _ (underscore) and \ (backslash) characters, as they have special meaning in LIKE arguments.

Change Log

Source File

wpdb::esc_like() is located in wp-includes/wp-db.php.

Related

See: Data Validation article for an in-depth discussion of input and output sanitization.


See also index of Function Reference and index of Template Tags.