php5.3 – mysqli_stmt:bind_params with call_user_func_array warnings

Possible Duplicate:
Is it possible to pass parameters by reference using call_user_func_array()?

I have the following line of code which worked in PHP 5.1, but isn’t working in PHP 5.3.

$input = array('ss','john','programmer');
call_user_func_array(array($mysqli_stmt, 'bind_param'), $input);

In PHP 5.3, I get the following warning message:

Warning: Parameter 2 to mysqli_stmt::bind_param() expected to be a reference, value given in /var/www/startmission/em/class/cls.data_access_object.php on line 785

I changed the code to the following and it worked:

$a = 'johnl';
$b = 'programmer';
$mysqli_stmt->bind_param('ss',$a,$b);

I found this in the php documentation:

Care must be taken when using mysqli_stmt_bind_param() in
conjunction with call_user_func_array(). Note that
mysqli_stmt_bind_param() requires parameters to be passed by reference,
whereas call_user_func_array() can accept as a parameter a list of
variables that can represent references or values.

So my question is, how do I replicate the functionality of the call_user_func_array + bind_params such that i can dynamically bind variables at run time?

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

I found the answer to my problem in a user note by fabio at kidopi dot com dot br3 years ago on the PHP manual page of mysqli_stmt::bind_param() (slightly modified):

I used to have problems with call_user_func_array and bind_param after migrating to php 5.3.

The cause is that 5.3 requires array values as reference while 5.2 worked with real values (but also with references). So I created a secondary helper function to help me with this:

function refValues($arr)
{ 
        $refs = array();

        foreach ($arr as $key => $value)
        {
            $refs[$key] = &$arr[$key]; 
        }

        return $refs; 
}

and changed my previous function from:

call_user_func_array(array($this->stmt, "bind_param"), $this->values); 

to:

call_user_func_array(array($this->stmt, "bind_param"), refValues($this->values)); 

This way my db functions keep working in PHP 5.2/5.3 servers.

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply