WordPress esc_sql() function is often used to escape a sql statement. In this tutorial, we will introduce some basic features on it.
Syntax
WordPress esc_sql() is defined as:
function esc_sql( $data ) { global $wpdb; return $wpdb->_escape( $data ); }
which means esc_sql() is the same to $wpdb->_escape().
How to use esc_sql()
We will use a simple example to show how to use it for wordpress beginners.
<?php $name = "alexa's"; echo esc_sql($name); ?>
Run this code, you will get the result.
alexa\'s
Then we can use $name in sql statement safely.
As to sql, we can use esc_sql() to escape some variables.
Here is an example:
$name=esc_sql($name); $status=esc_sql($status); $wpdb->get_var( "SELECT something FROM table WHERE foo = '$name' and status = '$status'" );
Of course, we also can use addslashes() to replace esc_sql().
For example:
$name=addslashes($name); $status=addslashes($status); $wpdb->get_var( "SELECT something FROM table WHERE foo = '$name' and status = '$status'" );
They are the same.