I am aware of array_walk() and array_map(). However when using the former like so (on an old project) it failed
array_walk($_POST, 'mysql_real_escape_string');
Warning: mysql_real_escape_string()
expects parameter 2 to be resource,
string given.
So I went with this slightly more ugly version
foreach($_POST as $key => $value) {
$_POST[$key] = mysql_real_escape_string($value);
}
So why didn’t the first way work? What is the best way to map values of an array to a function?
The callback function passed to
array_walkis expected to accept two parameters, one for the value and one for the key:But
mysql_real_escape_stringexpects the second parameter to be a resource. That’s why you’re getting that error.Use
array_mapinstead, it only takes the value of each item and passes it to the given callback function:The second parameter will be omitted and so the last opened connection is used.
If you need to pass the second parameter, you need to wrap the function call in another function, e.g. an anonymous function: