I need to escape array's, I am using array_map with mysqli_real_escape_string.
I have multiple arrays like
$_post['countries'];
$_post['categories'];
.
.
How do I perform escaping on these arrays
I am doing this way
$countries=array_map('mysqli_real_escape_string', $_POST['countries']);
$categories=array_map('mysqli_real_escape_string', $_POST['categories']);
.
.
but it shows me error as Warning: mysqli_real_escape_string() expects exactly 2 parameters, 1 given in
also doing
$categories=mysqli_real_escape_string($connection, $_POST['categories']);
gives error as
Warning: mysqli_real_escape_string() expects parameter 2 to be string, array given in
Please see and suggest a way or another better way to do this.
Thanks
You have a lot of solutions here.
Considering you wanna stick to mysqli (PDO is now the recommanded way, but still a choice) and you want to keep using array_map on this context, you have to check the array_map prototype: http://php.net/array_map
array array_map ( callable $callback , array $array1 [, array $... ] )
So:
Using dynamic arguments of array_map
Note : this solution is a bad one, and was mistaken.
Original answer : $myArray = array_map('mysqli_real_escape_string', $db, $myArray);
Updated answer : $myArray = array_map('mysqli_real_escape_string', $myArray, array_fill(0, count($myArray), $db)); and that's a bad idea with mysqli object.
Using array callable
Because mysqli_real_escape_string is also a method of mysqli...
$myArray = array_map(array($db, 'real_escape_string'), $myArray);
Using closure
$myArray = array_map(function($e) use($db) { return mysqli_escape_string($db, $e); }, $myArray);
or
$myArray = array_map(function($e) use($db) { return $db->real_escape_string($e); }, $myArray);
You need to wrap mysqli_real_escape_string() call with an anonymous function to use within array_map() like this:
// $connection_object is a mysqli object declared somewhere above
$countries = array_map(function($item) use($connection_object) {
return mysqli_real_escape_string($connection_object, $item);
}, $_POST['countries']);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With