Rivnat Nasah Rivnat Nasah - 4 months ago 91x
PHP Question

mysqli_real_escape_string Not working inside array_map

I have a function to making a insert query, But if i use

its not response with the values. This is the problem inside the array map so i can't figure out how to solve this.

Server version: 5.6.24 - MySQL Community Server (GPL)

My function is:

function insertQryStr($array, $table){
$insertUrl = "insert into %s(%s) values('%s')";
$insertQryStr = sprintf($insertUrl, $table, implode(', ',@array_map('mysql_real_escape_string', @array_keys($array))), implode("', '", @array_map('mysql_escape_string', $array)));
return $insertQryStr;


The call to array_map is failing because mysqli_real_escape_string when used as a function requires 2 arguments, the first being mysqli $link as per the documentation.

array_map doesn't know to pass a connection as the first argument. A better method would be from this answer.

To use this with your function, you'll need to pass in a link to the database.

function insertQryStr($array, $table, $link){
    array_walk($array, function(&$string) use ($link) { 
      $string = mysqli_real_escape_string($link, $string);

    $insertUrl = "insert into %s (%s) values('%s')";
    $insertQryStr = sprintf($insertUrl, $table, implode(', ',array_keys($array)), implode("', '", $array));
    return $insertQryStr;

Having said all that, instead of manually escaping data this way, you should check out and definitely use prepared statements