Insert multiple values in php mysql

后端 未结 1 962
天命终不由人
天命终不由人 2021-01-29 11:34

I have here a sample code for updating multiple value in php mysql. I wondering how I can insert multiple values?



        
1条回答
  •  走了就别回头了
    2021-01-29 11:51

    Use standard mysql insert statement with mysqli bind_param and php's call_user_func_array.

    $N = count($_POST['counter']);
    $query = "insert into table (column1, column2) values
              (?,?)". str_repeat(',(?,?)', $N-1);
    $st = $mysqli->prepare($query);
    $placeholders = str_repeat('s', $N*2);
    $params = array($placeholders);
    foreach($_POST['column1'] as $i => $c1) {
        $c2 = $_POST['column2'][$i];
        $params[] = $c1;
        $params[] = $c2;
    }
    call_user_func_array(array($st, 'bind_param'), refValues($params));
    $st->execute() or die($mysqli->error);
    $st->close();
    
    function refValues($arr){
        if (strnatcmp(phpversion(),'5.3') >= 0) //Reference is required for PHP 5.3+
        {
            $refs = array();
            foreach($arr as $key => $value)
                $refs[$key] = &$arr[$key];
            return $refs;
        }
        return $arr;
    }
    

    Mostly copied from here.

    0 讨论(0)
提交回复
热议问题