简体   繁体   中英

mysqli_real_escape_string Not working inside array_map

I have a function to making a insert query, But if i use mysqli_real_escape_string 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);
    });

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

Although a better idea would be to do this before calling insertQryStr() as to avoid tight coupling .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM