PDO Prepared Inserts multiple rows in single query

后端 未结 22 2077
感情败类
感情败类 2020-11-21 23:38

I am currently using this type of SQL on MySQL to insert multiple rows of values in one single query:

INSERT INTO `tbl` (`key1`,`key2`) VALUES (\'r1v1\',\'r1         


        
22条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2020-11-21 23:52

    You can insert multiple rows in a single query with this function:

    function insertMultiple($query,$rows) {
        if (count($rows)>0) {
            $args = array_fill(0, count($rows[0]), '?');
    
            $params = array();
            foreach($rows as $row)
            {
                $values[] = "(".implode(',', $args).")";
                foreach($row as $value)
                {
                    $params[] = $value;
                }
            }
    
            $query = $query." VALUES ".implode(',', $values);
            $stmt = $PDO->prepare($query);
            $stmt->execute($params);
        }
    }
    

    $row is an array of arrays of values. In your case you would call the function with

    insertMultiple("INSERT INTO tbl (`key1`,`key2`)",array(array('r1v1','r1v2'),array('r2v1','r2v2')));
    

    This has the benefit that you use prepared statements, while inserting multiple rows with a single query. Security!

提交回复
热议问题