RSS

MySQLi, bind_param and passing by reference issue

17 Mar

I use the following code to bind query params with MySQLi:

static function bindParams(&$stmt, $types, $valuesArray)     
{
	if (count($valuesArray) > 0)
	{
		$params = array_merge(array($types), $valuesArray);
		$bindOk = call_user_func_array(array($stmt,'bind_param'), $params);
	}
	else
	{
		$bindOk = true;
	}
	return $bindOk;
}

Never had any problem with this code until I run the php script with cron. I suddenly got this error “Error message: PHP Warning: Parameter 2 to mysqli_stmt::bind_param() expected to be a reference, value given”.

So the solution would be to “recreate” an array with parameters explicitly passing every parameter by reference. For example like this:

$params = array_merge(array($types), $valuesArray);

$tmpArray = array();
foreach ($params as $i => $value) 
{
    $tmpArray[$i] = &$params[$i];
}

Updated code would then look something like that:

static function bindParams(&$stmt, $types, $valuesArray)     
{
	if (count($valuesArray) > 0)
	{
		$params = array_merge(array($types), $valuesArray);
		
		$tmpArray = array();
        foreach ($params as $i => $value) 
		{
   	 		$tmpArray[$i] = &$params[$i];
		}
		
		$bindOK = call_user_func_array(array($stmt,'bind_param'), $tmpArray);
	}
	else
	{
		$bindOK = true;
	}
	return $bindOK;
}

The only open question is why executing code with cron suddenly revealed the issue. If you know the answer, please post the comment! Thanks.

Advertisements
 
3 Comments

Posted by on March 17, 2011 in PHP

 

Tags: , ,

3 responses to “MySQLi, bind_param and passing by reference issue

  1. Dam

    March 17, 2011 at 5:13 pm

    probably it’s due to the php.ini configuration.
    Cron runs the php script from cli, so the php.ini file called is /etc/php5/cli/php.ini rather than /etc/php5/apache2/php.ini and they are generally different

     
    • Dasha

      March 17, 2011 at 7:54 pm

      So does this mean that if I specify the path to the correct php executable it should fix it? Or will it still use wrong config?

       
      • Dam

        March 17, 2011 at 8:37 pm

        well the –php-ini option for the php command should load the apache php.ini file but it might possible that you get into some other troubles. It depends on the options set in the apache php.ini file.

        of course, you could try it just for debug and see what happens.

         

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: