To avoid the problem BPAT was alluding to, you can let the function "decide" whether the value needs to be quoted, e.g.:
function clean($data)
{
if(get_magic_quotes_gpc())
{
$data = stripslashes($data);
}
if(!is_numeric($data))
{
$data = "'" . mysql_real_escape_string($data) . "'";
}
return $data;
}
// Sample usage
$sql = "SELECT * FROM table_name WHERE id=" . clean($_POST['id'])
. " AND col_1=" . clean($_POST['col1'];
Note that where I typed the sample SQL string, no quotes were put around either value -- even though I expect the "col1" value to be a string -- as the clean() function will now handle it for me when needed.
Another option is to use sprintf() to force the numeric type as applicable (e.g. via the %d or %f place-holders), in which case you could choose not to have the function add the quotes around strings if you prefer not to:
function clean($data)
{
if(get_magic_quotes_gpc())
{
$data = stripslashes($data);
}
if(!is_numeric($data))
{
$data = mysql_real_escape_string($data);
}
return $data;
}
// Sample usage
$sql = sprintf(
"SELECT * FROM table_name WHERE id=%d AND col1='%s'",
clean($_POST['id']),
clean($_POST['col1'])
);
Or you could just use mysqli (or PDO) and prepared statements with bound parameters, and be done with all this fun. 😉