wpdb::_real_escape()publicWP 2.8.0

Escapes a string for safe insertion into an SQL query using mysqli_real_escape_string().

Before returning, it replaces % characters with the internal WordPress placeholder.

The method is used internally by wpdb::_escape(), wpdb::prepare(), and wpdb::escape_by_ref(). In most cases, use wpdb::prepare() instead of calling this method directly.

This method requires a database connection. Without one, WordPress issues an incorrect-usage warning and escapes the value with addslashes().

Method of the class: wpdb{}

Used By: wpdb::_escape()
1 time — 0.0000081 sec (speed of light) | 50000 times — 0.05 sec (speed of light)

No Hooks.

Returns

String.

  • string - the escaped string.
  • '' - if a non-scalar value was passed.

Usage

global $wpdb;
$wpdb->_real_escape( $data );
$data(string) (required)
The string to escape.

Examples

#1 String escaping

global $wpdb;
$value = $wpdb->_real_escape( "O'Reilly" ); // O\'Reilly

Notes

  • See: mysqli_real_escape_string()

Changelog

Since 2.8.0 Introduced.

wpdb::_real_escape() code WP 7.0.4

public function _real_escape( $data ) {
	if ( ! is_scalar( $data ) ) {
		return '';
	}

	if ( $this->dbh ) {
		$escaped = mysqli_real_escape_string( $this->dbh, $data );
	} else {
		$class = get_class( $this );

		wp_load_translations_early();
		/* translators: %s: Database access abstraction class, usually wpdb or a class extending wpdb. */
		_doing_it_wrong( $class, sprintf( __( '%s must set a database connection for use with escaping.' ), $class ), '3.6.0' );

		$escaped = addslashes( $data );
	}

	return $this->add_placeholder_escape( $escaped );
}