3

Possible Duplicate:
mysql_fetch_array() expects parameter 1 to be resource, boolean given in select

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

Community
  • 1
  • 1
xkeshav
  • 53,360
  • 44
  • 177
  • 245

2 Answers2

9

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);
Dan Soap
  • 10,114
  • 1
  • 40
  • 49
  • Casey, I was just about to post this. Good answer. – Mike Sherov Jan 31 '10 at 22:12
  • @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 – xkeshav Jan 31 '10 at 22:22
  • 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. – Dan Soap Jan 31 '10 at 23:10
6

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

Tyler Carter
  • 60,743
  • 20
  • 130
  • 150