RSS

Monthly Archives: March 2011

MySQLi, bind_param and passing by reference issue

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: , ,

 
%d bloggers like this: