How to call mysqli_stmt with call_user_func_array?

2019-07-23 18:05发布

问题:

I am trying to pass a variable number of arguments to a method of a class. Here is the function of the class that I am trying to invoke:

class DbHelper{
....
    public function Execute($query, $params){
        $this->open();
        $stmt = $this->mysqli->prepare($query) or die($this->mysqli->error);
        call_user_func_array(array($stmt, 'bind_param'), $params);  // 1
        return $stmt->execute() ? $stmt->num_rows : 'ERROR';
    }
....
}

Here is the code I am using to invoke the function:

....
$conn = new DbHelper();
$params = array('ss', $ID, $i);
$conn->Execute('INSERT INTO some_table (ID, `Index`) VALUES (?,?)', $params);
....

This gives an error:

Warning: Parameter 2 to mysqli_stmt::bind_param() expected to be a reference, value given in ..mypath..\dbhelper.php on line

In my another post (click here) on same issue few months back, some on suggested me to use the code below:

call_user_func_array(array($stmt, 'bind_param'), refValues($params));

function refValues($arr){
    if (strnatcmp(phpversion(),'5.3') >= 0){ //Reference is required for PHP 5.3+
        $refs = array();
        foreach($arr as $key => $value)
            $refs[$key] = &$arr[$key];
        return $refs;
    }
    return $arr;
}

Using this again gives the same error. If I invoke the function like this (adding & before $params):

$conn->Execute('INSERT INTO some_table (ID, `Index`) VALUES (?,?)', &$params); // 2

I get this error:

Deprecated: Call-time pass-by-reference has been deprecated in ..mypath..\save.php on line

Alternatively, I have tried this definition for function DbHelper::Execute:

public function Execute($query, $params){
    $this->open();
    $stmt = $this->mysqli->prepare($query) or die($this->mysqli->error);
    $stmt->{'bind_param'}($params); // 3
    return $stmt->execute() ? $stmt->num_rows : 'ERROR';
}

Invoking this shows the error as:

Warning: Wrong parameter count for mysqli_stmt::bind_param() in ..mypath..\dbhelper.php on line

Where as, the parameter count is correct to bind_param, if the function is called properly.

The version of PHP is 5.3.8.

Any help please?

回答1:

The function that has been suggested to you needs to accept $params via reference as well. Here's a slightly updated version:

function refValues(&$arr)
{
    //Reference is required for PHP 5.3+
    if (strnatcmp(phpversion(),'5.3') >= 0)
    {
        $refs = array();
        foreach(array_keys($arr) as $key)
        {
            $refs[$key] = &$arr[$key];
        }
        return $refs;
    }

    return $arr;
}


标签: php mysqli