如何在 php 的 foreach 循环中使用两个数组或三个数组插入数据库

how to use two arrays or three arrays in the foreach loop in php for insert to database

如何在数据库行中使用 foreach 插入多个数组?

这不是数组的问题,但我的问题是使用两个或更多数组。

我的php代码:

$checkBox1 = implode(',', $_POST['goinput1']);
$checkBox2 = implode(',', $_POST['goinput3']);
$mark3=explode(',', $checkBox1);
$mark4=explode(',', $checkBox2);
foreach($mark3 as $out3) 
{
    $sql_sub = "INSERT INTO sub_forms
                        (bord_mizban,bord_mihman) 
                VALUES ('$out3','$out4')";      
    if ($conn->query($sql_sub) === TRUE) {  

    } else {

    }   

}

** 我想用 out 3 变量将 out 4 变量插入到数据库中 **

使用索引 ($key) 遍历 $mark3 并获取同一键下的元素:

foreach($mark3 as $key => $out3) 
{
    echo $out3 . '; ' . $mark4[$key];
}

简短的回答是:

foreach($mark3 as $key => $out3) {
    $values = "'$out3."','".$mark4[$key]."'"
    $sql_sub = "INSERT INTO sub_forms
                        (bord_mizban,bord_mihman) 
                VALUES ($values)";      
    if ($conn->query($sql_sub) === TRUE) {  

    } else {

    }   

}

这将解决您的实际问题。但是,有更好的方法可以做到这一点,只需 1 sql 个查询。

foreach($mark3 as $key => $out3) {
    $valuesArray[] = "('$out3."','".$mark4[$key]."')" // this makes an array of your value sets.
}
$values = join(", ", $valuesArray) // this joins your array to one string, with each entry separated by a comma.
$sql_sub = "INSERT INTO sub_forms
                        (bord_mizban,bord_mihman) 
                VALUES $values";      
    if ($conn->query($sql_sub) === TRUE) {  

    } else {

    }