如何使用预准备语句插入多行

时间:2013-10-09 11:47:51

标签: php mysqli prepared-statement sql-insert

我使用了一个非常简单的插入语句

INSERT INTO table (col1, col2, col3) VALUES (1,2,3), (4,5,6), (7,8,9), ...

目前,包含要插入的值的查询部分是在循环中构造的单独字符串。

如何使用预准备语句插入多行?

编辑:我找到了这段代码。但是,这会对每一行执行单独的查询。这不是我想要的。

$stmt =  $mysqli->stmt_init();
if ($stmt->prepare("INSERT INTO table (col1, col2, col3) VALUES (?,?,?)")){ 
    $stmt->bind_param('iii', $_val1, $_val2, $_val3);
    foreach( $insertedata as $data ){
        $_val1 = $data['val1'];
        $_val2 = $data['val2'];
        $_val3 = $data['val3'];
        $stmt->execute();
    }
}

编辑#2 :我的值来自可变长度的多维数组。

$values = array( array(1,2,3), array(4,5,6), array(7,8,9), ... );

1 个答案:

答案 0 :(得分:1)

这通常只是我在为包含IN子句的查询编写预准备语句时使用的技术。无论如何,我已经调整它以形成一个准备好的查询(而不是迭代准备的查询),我测试它在我的服务器上是成功的。这个过程有点复杂,我不知道速度是否有任何优势(没有基准)。这真的不是开发人员在生产中烦恼的事情。

代码:

if (!$mysqli = new mysqli($config[0], $config[1], $config[2], $config[3])) {
    echo "connection bonk";
} else {
    $array = [[1, 2, 3],[4, 5, 6], [7, 8, 9]];  // sample indexed array of indexed arrays
    $params = [];
    foreach ($array as $row) {
        $parentheticals[] = '('.implode(',', array_fill(0, sizeof($row), '?')).')';  // build parentheticals
        $params = array_merge($params, $row);  // flatten actual values to 1-dim array
    }
    $values = implode(',', $parentheticals);
    $count = sizeof($params); // assuming you have balanced subarrays

    if ($stmt = $mysqli->prepare("INSERT INTO test (col1, col2, col3) VALUES $values")) {
        array_unshift($params, str_repeat('i', $count));  // prepend the type values string
        $ref = [];  // add references
        foreach ($params as $i=>$v) {
            $ref[$i] = &$params[$i];  // pass by reference as required/advised by the manual
        }
        call_user_func_array([$stmt, 'bind_param'], $ref);    

        if ($stmt->execute()) {
            echo $stmt->affected_rows , " affected rows";  // how many rows were inserted
        } else {
            echo "execution bonk";
        }
        $stmt->close();
    } else {
        echo "prepare bonk";
    }
}