Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Escaping arrays using mysqli escape string [duplicate]

Tags:

arrays

php

mysqli

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


2 Answers

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:

  1. 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.

  2. Using array callable

    Because mysqli_real_escape_string is also a method of mysqli... $myArray = array_map(array($db, 'real_escape_string'), $myArray);

  3. 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);

like image 169
Lpu8er Avatar answered Mar 09 '26 10:03

Lpu8er


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']);
like image 21
Max Zuber Avatar answered Mar 09 '26 10:03

Max Zuber