2

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 
)
1
  • If you want to use references to pass the result to wherever you call the function from, you need to use & on every step. I.e. insertUsers($db, $sql, &$vals), foreach($vals as $key=>&$value). Commented Dec 15, 2017 at 20:47

2 Answers 2

4

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){
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.