简体   繁体   中英

How can I pass a connection object to a closure

I have the following code to escape posted data:

if (isset($_POST['submitted'])) {
    $trimmed_post = array_map('trim', $_POST);

    $bk = mysqli_real_escape_string($dbc, $trimmed_post['bk_id']);
    $ad = mysqli_real_escape_string($dbc, $trimmed_post['address']);
    $ti = mysqli_real_escape_string($dbc, $trimmed_post['bkTitle']);
    $ta = mysqli_real_escape_string($dbc, $trimmed_post['tags']);
    $de = mysqli_real_escape_string($dbc, $trimmed_post['description']);

but I would prefer to do this - it's neater:

list($bk, $ad, $ti, $ta, $de) = array_map(function ($x) {
    return mysqli_real_escape_string($dbc, $x);
}, $trimmed_post);

I'm using MySql 5.5.16, but it returns "Undefined variable: dbc".

I suspect it is a 'closure' issue. How can I pass $dbc into my lambda pl?

You can use the use keyword.

list($bk, $ad, $ti, $ta, $de) = array_map(function ($x) use ($dbc) {
    return mysqli_real_escape_string($dbc, $x);
}, $trimmed_post);

But honestly, you should be using 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