I'm trying pass an array as a function's parameters, and am having some trouble. Here's the function.
$stmt->bind_param();
I was researching this and found that you can use this:
$stmt->bind_param(...$values);
This worked well on my developmental server (PHP 7.0.0), but when I inputted it into another server (PHP 5.*), I got the following error:
syntax error, unexpected '.', expecting ')'
Upon further research, I tried:
call_user_func_array(array($stmt, 'bind_param'), $values);
and got this error:
call_user_func_array() expects parameter 1 to be a valid callback, first array member is not a valid class name or object
I know that I could just input the parameters and everything will work out fine, but I need the function to take any number of parameters (which is what led to the function idea).
Here's the function:
function updateId($id, $data){
$mysqli = dbConnect::connect();
$sm=array();
$values=array();
$dataString = array();
foreach($data as $column=>$value){
$dataString[] = ($column .'= ?');
$values[] = $value;
if(gettype($value)==="string"){
$sm[] = 's';
}elseif(gettype($value)==="integer"){
$sm[] = 'i';
}elseif(gettype($value)==="double"){
$sm[] = 'd';
}else{
$sm[] = 'b';
}
}
$dataString = implode(', ',$dataString);
$sm = implode('',$sm);
$prepString = "UPDATE $this->tablename SET $dataString WHERE id=$id";
array_unshift($values, $sm);
$stmt = $mysqli->prepare($prepString);
$stmt->bind_param(...$values);
$stmt->execute() or die($stmt->error);
$stmt->close();
$mysqli->close();
}
You are getting an error because you pass non-reference values to bind_param
. You can use call_user_func_array
, but you must make sure that the values you pass are references. This you can achieve as follows:
Change this:
$values[] = $value;
to this:
$values[] = &$data[$column];
And (like you already did) change this:
$stmt->bind_param(...$values);
into this:
call_user_func_array(array($stmt, 'bind_param'), $values);