8

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?

1
  • this is not a duplicate of the one linked to. this is specifically about call_user_func_array WITH mysqli. the linked to question has no relationship with mysqli at all. Commented Mar 21, 2014 at 16:12

1 Answer 1

13

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.

Sign up to request clarification or add additional context in comments.

2 Comments

This refValues function doesn't compile. It has number of curly braces mismatch... Can you fix it?
you need to add types first. $types = 'ss', array_unshift($input,$types); then above function will work prefectly. thank you john.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.