On a few of my sites, I use a small snippit of code to automatically escape all $_POST variables (also $_GET variables) to be safe to use in MySQL queries. It's made up of two parts. The first is the code that checks to see if $_POST (or $_GET) is empty; second is the escaping function which either uses array_walk_recursive() or array_map() depending on your PHP version.
Also, a word of warning. mysql_real_escape_string() requires an active MySQL connection to function, so be sure to place the variable check snippit after your database connection string.
Variable check:
PHP Code:
if (!empty($_POST) && is_array($_POST)) {
recurse_escape_mysql($_POST);
}
recurse_escape_mysql():
PHP Code:
function recurse_escape_mysql(&$var, $key = NULL){
if (function_exists('array_walk_recursive')) {
if(is_array($var)){
array_walk_recursive($var, 'recurse_escape_mysql');
} else {
if (get_magic_quotes_gpc()) {
$var = stripslashes($var);
}
$var = mysql_real_escape_string($var);
}
} else {
if(is_array($var)){
$var = array_map('recurse_escape_mysql', $var);
} else {
if (get_magic_quotes_gpc()) {
$var = stripslashes($var);
}
$var = mysql_real_escape_string($var);
}
return $var;
}
}