Pari Baker
Pari Baker

Reputation: 716

foreach loop populate array for call_user_func_array

I am using a foreach loop to populate an array with parameter types and parameter values before it inserts into the database. Everything works fine and posts to the db, but I can't figure out why it sends both values as the same when they are added (as a reference) to the array. I have tired calling unset(); but it doesn't do the trick.

function insertUsers($db, $sql, $vals){
     $stmt= $db->prepare($sql);
     $types='';
     $types= $types ?: str_repeat("s", count($vals));
     $inputArray [] = &$types;

     foreach($vals as $key=>$value){
         $inputArray[]= &$value;
         unset($key);
     }
     print_r($inputArray);

     call_user_func_array(array($stmt, 'bind_param'), $inputArray);
     $stmt->execute();
     $stmt->close();
 }

The result ends being:

Array
(
  [0] => ss
  [1] => tyuty (note this value changes to the last value)
  [2] => tyuty 
)

Upvotes: 2

Views: 287

Answers (2)

Dharman
Dharman

Reputation: 33305

It's much better to avoid using call_user_func_array() for exactly this reason. Since PHP 5.6 we have a splat operator (...) that helps you avoid all this hassle.

Simply unpack the array directly in the call to bind_param().

function insertUsers($db, $sql, $vals){
    $stmt = $db->prepare($sql);
    $stmt->bind_param(str_repeat("s", count($vals)), ...$vals);
    $stmt->execute();
}

Upvotes: 0

Death-is-the-real-truth
Death-is-the-real-truth

Reputation: 72299

You need to remove & from there inside foreach();-

foreach($vals as $key=>&$value){ // put & here
  $inputArray[]= $value; // remove & from here and unset() not needed actually
}

And Add & inside function argument too:-

function insertUsers($db, $sql, &$vals){

Upvotes: 4

Related Questions