2

I haven't yet learned how to use parameterized queries (which according to some other posts on this site is something that I absolutely need to do first thing tomorrow morning) and I want to get a whack of form data into a query, escaped.

Twice, I have come across this solution:

$_POST = array_map('mysqli_real_escape_string', $_POST);

This, from what I can tell, runs all of the variables in the $_POST array through the escape function. I have seen that exact line upvoted, but when I add it to my existing PHP it creates a bunch of blank values.

I was under the impression that mysqli_real_escape_string needed a 2nd parameter - the link/connection. Is this what's causing my problem? The data takes just fine in the database if that line is removed and my variables take their unescaped values from $_POST.

4

3 回答 3

3

array_map returns new array, if you're overwriting $_POST, better solution would be to use array_walk.

array_walk($_POST, function(&$string) use ($link) { 
  $string = mysqli_real_escape_string($link, $string);
});

Note that $link must be valid connection.

Function [ <internal:mysqli> function mysqli_real_escape_string ] {

  - Parameters [2] {
    Parameter #0 [ <required> $link ]
    Parameter #1 [ <required> $string_to_escape ]
  }
}
于 2013-09-05T00:30:34.473 回答
2

You must pass values ​​escaped to another variable:

$post = array_map('mysqli_real_escape_string', $_POST);

Or:

foreach($_POST as $k => $v) {
    $_POST[$k] = mysqli_real_escape_string($v);
}

Note: Unless the array is referenced, foreach operates on a copy of the specified array and not the array itself.

于 2013-09-05T00:13:30.260 回答
0

Then yes this is your answer:

mysql_real_escape_string() requires a connection to the database as it uses the database's character set to determine what is needed to be escaped.
Without this, PHP has no idea what char set you're using and so what to escape.

There are many:
http://dev.mysql.com/doc/refman/5.0/en/charset-unicode-sets.html
And all with different chars.

于 2013-09-05T00:15:39.087 回答