1

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();

}
Dharman
  • 30,962
  • 25
  • 85
  • 135
Blaise
  • 330
  • 1
  • 11

1 Answers1

1

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);
trincot
  • 317,000
  • 35
  • 244
  • 286
  • Thank you so much. What's the difference between $values[] = $value; and $values[] = &$data[$column];? – Blaise Oct 05 '16 at 19:55
  • 1
    The difference is visible when you `var_dump` the array after the loop: with the changed code you see a `&` before each value, meaning it really are pointers (or addresses) referring to the actual value. This is what `bind_param` needs. I suppose it needs this for making it possible to deal with output parameters, which is not your case, but could be the case when calling stored procedures/functions. – trincot Oct 05 '16 at 20:06