On a PHP file, I receives more than 20 variables coming from the client(submitted via a web form) and I have to apply mysql_real_escape_string() more than 20 times, it is quite troublesome, is there a better way to do this job?
views:
179answers:
4No, that is the best way. As answered in this old question, you should always use whatever tools the language/system has available for you.
However, your issue still remains about it being tedious. I'd suggest a loop. Assuming your variables are in $_POST
:
$vars = array("foo", "bar", "baz"); // names of variables
foreach ($vars as $var) {
// tricky $$ usage will create the variables
// $foo, $bar, etc., with the escaped values.
${$var} = mysql_real_escape_string($_POST[$var]);
// you could also store an array of inputs, like $inputs[$var] = ...;
}
like, foreach?
$names = array('foo', 'bar', 'baz');
$inputs = array();
foreach ($names as $name) {
$inputs[$name] = mysql_real_escape_string($_POST[$name]);
}
you can use array_map also
$_POST = array_map('mysql_real_escape_string',$_POST);
is there a better way to do this job?
Certainly: parameterised queries.
They're a little bit wordy in PHP, and unfortunately since they require you to move to mysqli
(or some other data access layer that provides the feature, and maybe others like database-independence), instead of the old mysql_
functions there would have to be some rewriting. But taking the SQL string literal escaping out of your application and putting it in the data access layer where it belongs is a big improvement.