foreach循环填充call_user_func_array的数组

时间:2017-12-15 20:15:33

标签: php mysqli

我使用foreach循环在插入数据库之前使用参数类型和参数值填充array。一切正常,并发布到数据库,但我无法弄清楚为什么它们({作为参考)添加到array时发送两个值相同。我已经厌倦了呼叫unset();,但它没有做到这一点。

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

结果结束:

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

2 个答案:

答案 0 :(得分:2)

您需要从&内删除foreach(); -

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

并在函数参数中添加 &: -

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

答案 1 :(得分:0)

正是出于这个原因,最好避免使用 call_user_func_array()。从 PHP 5.6 开始,我们有一个 splat operator (...) 可以帮助您避免所有这些麻烦。

只需在调用 bind_param() 时直接解压缩数组。

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