I'm basically trying to call mysqli::bind_param via call_user_func_array
.
Here's my function:
function Insert($table, $values=array(), $flags=0) {
$field_count = count($values);
if($field_count > 0) {
$fields = implode(',',array_keys($values));
$placeholders = implode(',',array_repeat('?',$field_count));
} else {
$fields = '';
$placeholders = '';
}
if($flags > 0) {
$flag_arr = array();
if($flags & self::LOW_PRIORITY) $flag_arr[] = 'LOW_PRIORITY';
if($flags & self::DELAYED) $flag_arr[] = 'DELAYED';
if($flags & self::HIGH_PRIORITY) $flag_arr[] = 'HIGH_PRIORITY';
if($flags & self::IGNORE) $flag_arr[] = 'IGNORE';
$flags_str = implode(' ',$flag_arr);
} else {
$flags_str = '';
}
$sql = "INSERT $flags_str INTO $table ($fields) VALUES ($placeholders)";
$stmt = $this->mysqli->prepare($sql);
if($stmt === false) {
throw new Exception('Error preparing MySQL statement.<br/>MSG: '.$this->mysqli->error.'<br/>SQL: '.$sql);
}
if($field_count > 0) {
$types = '';
foreach($values as $val) {
if(is_int($val)) $types .= 'i';
elseif(is_float($val)) $types .= 'd';
elseif(is_string($val)) $types .= 's';
else $types .= 'b';
}
$params = array_merge(array($types),array_values($values));
call_user_func_array(array($stmt,'bind_param'),$params);
}
$stmt->execute();
return $stmt;
}
The problem occurs on the call_user_func_array
line. I get this error:
Parameter 2 to mysqli_stmt::bind_param() expected to be a reference, value given
I understand the problem, I'm just not sure how to work around it.
As an example, the function may be called like this:
$db->Insert('pictures',array('views'=>1));
And var_dump($params)
would yield this:
array
0 => string 'i' (length=1)
1 => int 1
So, is there a way to call mysqli::bind_param
with a variable number of arguments, or somehow make my array into references?