tags:

views:

310

answers:

2

when i use

array_map('mysql_real_escape_string', $_POST);

it display

    Warning: mysql_real_escape_string() expects parameter 1 to be string, array given in D:\xampp\htdocs\...\...\xyz.php on line 14

what is the reason after that?

EDIT: and if i use

array_walk_recursive($_POST, 'mysql_real_escape_string');

then it display

Warning: mysql_real_escape_string() expects parameter 2 to be resource, integer given in D:\xampp\htdocs\..\...\xyz.php on line 17

please also tell me the difference above both method? Thank You in advance

+4  A: 

Is it possible that on of the values of your $_POST is an array?

Does your form look something like:

<input type="text" name="value[]">

or do any of the names have [] in them? That would cause an array to be in the $_POST data.

Try var_dumping your $_POST and see if any of the values are arrays.

If it is an array, then you have a problem, as mysql_real_escape_string won't take an array as a parameter. In which case you would want to look at Cassy's function to do it recursively.


You may want to try reading the documentation to find the difference between the two functions:

In array_walk_recursive, the function its being passed to recieves a key as a second parameter, while array_map doesn't.

(PHP has a really great documentation. Use it.)

Chacha102
yes it have the array within array
diEcho
Your answer is also good and helping.
diEcho
+3  A: 

I assume that one of the elements of $_POST is indeed an array, visualised something like this:

print_r($_POST);

Array
(
 ...
    'element' => Array
    (
        'subelement' => 'some value'
    )
 ...
)

When array_map tries to give the value of $_POST['element'] to mysql_real_escape_string, it throws the error you describe.

You could try to wrap the call though, something along this (untested) function:

function recursive_escape(&$value) {
    if (is_array($value))
        array_map('recursive_escape', $value);
    else
        $value = mysql_real_escape_string($value);
}

array_map('recursive_escape', $_POST);
Cassy
Casey, I was just about to post this. Good answer.
Mike Sherov
@Cassy - Thank You Sir, one last query, after applying this function may i use `$_post['variable']` directly in mysql query or i need to save post array in another array via applying above function
diEcho
Same problem here: If `$_POST['variable']` is an array, you still need to unwind it before you can pass it on to mysql. If it is a scalar (i.e. string or int) you can use it right away.
Cassy