如何在mysql过程中插入100条记录,在mysql过程中循环而不是在php中?

aelbi1ox  于 2021-06-20  发布在  Mysql
关注(0)|答案(1)|浏览(388)

我有一个100或200个问题的记录,当用户提交测试所有100或200个问题从缓存需要保存到mysql。现在我必须在php中循环,每次执行一个查询时,任何关于如何在mysql过程中发送数组和100或200的循环的想法都应该在mysql过程中完成。我可以将数组转换为json,因为mysql支持json。
需要插入的数组如下所示

Array
(
[0] => Array
    (
        [0] => 19287
        [1] => 1
        [2] => 1
        [3] => 101
        [4] => 224
        [5] => 0
    )

[1] => Array
    (
        [0] => 19285
        [1] => 0
        [2] => 1
        [3] => 101
        [4] => 2
        [5] => 0
    )

[2] => Array
    (
        [0] => 19289
        [1] => 1
        [2] => 1
        [3] => 72
        [4] => 23
        [5] => 0
    )

[3] => Array
    (
        [0] => 19290
        [1] => 
        [2] => 1
        [3] => 106
        [4] => 3
        [5] => 0
    )

[4] => Array
    (
        [0] => 19291
        [1] => 0
        [2] => 1
        [3] => 230
        [4] => 76
        [5] => 0
    )
)
brccelvz

brccelvz1#

可以构建多行 INSERT 在php代码中。假设你的数据在 $arr :

$sql = "INSERT INTO yourtable (...column list...) VALUES ";
$vsets = array();
foreach ($arr as $values) {
    $vsets[] = str_replace(array(',,', ',,'), ',NULL,', "(" . implode(',', $values) . ")");
}
$sql .= implode(',', $vsets);
echo $sql;

输出:

INSERT INTO yourtable (...column list...) 
    VALUES (19287,1,1,101,224,0),(19285,0,1,101,2,0),
           (19289,1,1,72,23,0),(19290,NULL,1,106,3,0),
           (19291,0,1,230,76,0)

确保过滤、验证或强制转换数据,以防止任何非整数(或任何sql)被注入到查询中。

相关问题