douyan1244
2019-02-23 12:30
浏览 236
已采纳

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

How to insert multiple arrays with a foreach in rows of databases?

It's not a problem with an array, but my problem is to use two arrays or more.

my php code:

$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 {

    }   

}

** I want the out 4 variable insert to the database with the out 3 variable **

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • dongyi6543 2019-02-23 12:49
    已采纳

    Iterate over $mark3 using indexes ($key) and get element under same key:

    foreach($mark3 as $key => $out3) 
    {
        echo $out3 . '; ' . $mark4[$key];
    }
    
    已采纳该答案
    打赏 评论
  • dongsha9208 2019-02-23 13:06

    The short answer is:

    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 {
    
        }   
    
    }
    

    That would fix your actual question. However, there is a better way to do this, with only 1 sql query.

    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 {
    
        }   
    
    打赏 评论

相关推荐 更多相似问题