Error with array_walk_recursive and mysqli :: real_escape_string
I am using object oriented style for my mysql connection, but if I write this:
array_walk_recursive($_POST, array($mysqli, 'real_escape_string'));
I am getting this error:
Warning: mysqli::real_escape_string() expects exactly 1 parameter, 2 given
The point is that mysqli :: escape_string only takes one parameter :
string mysqli::escape_string ( string $escapestr )
Writing:
$VAR = array();
$VAR = $_POST;
function escape_string($item, $key) {
$arr[$key] = $mysqli->real_escape_string($item);
}
array_walk_recursive($VAR, 'escape_string');
And I am getting this error:
Fatal error: Call to a member function real_escape_string() on a non-object
source to share
You need to pass the string as second argument, not an array:
function escape_string($item, $key) {
// Echo them out (using procedural mysqli)
echo mysqli_real_escape_string($item);
// or collect them in an array (using OOP mysqli)
$arr[$key] = $mysqli->real_escape_string($item);
}
array_walk_recursive($_POST, 'escape_string');
source to share
See the definition of array_walk_recursive .
Typically, funcname takes two parameters. The input parameter value is the first and the second / index is the second.
As you correctly point out:
The point is that mysqli :: escape_string only takes one parameter:
So wrap real_escape_string()
in a function that takes two parameters.
You might need to try array_map
, but recursive.
function array_map_recursive($fn, $arr) {
$rarr = array();
foreach ($arr as $k => $v) {
$rarr[$k] = is_array($v)
? array_map_recursive($fn, $v)
: $fn($v); // or call_user_func($fn, $v)
}
return $rarr;
}
Here: http://php.net/manual/en/function.array-map.php#107808
Or something like this (using "ref");
function array_map_recursive2($fn, &$arr) {
foreach ($arr as $k => $v) {
$arr[$k] = is_array($v)
? array_map_recursive2($fn, $v)
: $fn($v);
}
return $arr;
}
$a = array(1,2,array(5,array(6)));
array_map_recursive2(function($v){
return $v * 2;
}, $a);
print_r($a);
Array ( [0] => 2 [1] => 4 [2] => Array ( [0] => 10 [1] => Array ( [0] => 12 ) ) )
source to share