从$_POST数组多次插入到MySQL


Multiple INSERT INTO MySQL from $_POST array

我从一个表单接收以下数组:

array (size=1)
    'checkbox' => 
array (size=2)
    0 => string '14' (length=2)
    1 => string '13' (length=2)
    2 => string '15' (length=2)
array (size=1)
    'id' => string '1' (length=1)

我需要建立一个查询看起来像这样:

$sql = "INSERT INTO table(column1,column2) VALUES (14,1),(13,1),(15,1)";
第一个数组将根据每次选中的复选框而有所不同。

好吧,你可以尝试在这个数组上使用foreach循环。假设您将复选框命名为name="checkbox[]"

然后在处理$_POST变量的页面上,您可以执行

$sql = "INSERT INTO table(column1,column2) VALUES (?,?)";
$stmt = $mysqli->prepare($sql);
foreach ($_POST['checkbox'] as $box) {
    //process each checkbox here
    $stmt->bind_param('ss', $box, $otherValue);
    $stmt->execute();
}

这只是一个伪代码,让你开始。

您可以在这里找到有关预处理语句的更多信息:http://php.net/manual/en/mysqli-stmt.bind-param.php

// Create an empty array to store each checkbox value
$values = array();
if(is_array($_POST['checkbox'])){
    foreach($_POST['checkbox'] as $checkbox){
        foreach($checkbox as $key => $value){
            // add each checkbox value to an array
            $values[] = ($value,$_POST['id']);
        }
    }
}
// if the array has values..
if(count($values)){
    // implode the values into a string..
    $sqlValues = implode(',',$values);
    // ..and use that string in the query
    $sql = "INSERT INTO table(column1,column2) VALUES $sqlValues";
}