来自 $_POST 数组的多个 INSERT INTO MySQL

2022-01-09 00:00:00 arrays post insert php mysql

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

I am receiving the following arrays from a form:

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)

我需要构建一个如下所示的查询:

I need to build a query looking like this:

$sql = "INSERT INTO table(column1,column2) VALUES (14,1),(13,1),(15,1)";

根据选中的复选框,第一个数组每次都会有所不同.

And the first array will be different every time based on the checked checkboxes.

推荐答案

好吧,您可以尝试在该数组上使用 foreach 进行循环.因此,假设您已将复选框命名为 name="checkbox[]".

Well, you can try looping with a foreach on that array. So let's say you have named your checkboxes as name="checkbox[]".

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

Then on the page where you are processing the $_POST vars you can do

$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();
}

这只是一个让您入门的伪代码.

This is just a pseudo-code to get you started.

您可以在此处找到有关准备好的语句的更多信息:http:///php.net/manual/en/mysqli-stmt.bind-param.php

You can find more info on prepared statements here: http://php.net/manual/en/mysqli-stmt.bind-param.php

相关文章