【问题标题】:insert using multiple foreach inside for each only gets the final value in every foreach在每个 foreach 中使用多个 foreach 插入仅在每个 foreach 中获取最终值
【发布时间】:2019-05-25 16:54:55
【问题描述】:

我目前正在开发一个评估系统。问题是动态创建的/

所以我已经尝试从不同的 foreach 输入字段插入值,我使用输入类型文本而不是单选按钮。我的代码只是插入从每个 foreach 循环中获取的最后一个值。

 <?php 
    session_start();
    include('connectDB.php');
    $userId= $_SESSION['id'];

    mysqli_query($conn,"UPDATE student SET evaluationId = 1 WHERE studentId='$userId'");

    foreach($_POST['nPersonnelId'] as $personnelId ){
        for ($i=0; $i<count($_POST['rCourteous']); $i++){
            $rCourteous = $_POST['rCourteous'][$i];
        }
        for ($i=0; $i<count($_POST['rPrompt']); $i++){
            $rPrompt = $_POST['rPrompt'][$i];
        }
        for ($i=0; $i<count($_POST['rCompetent']); $i++){
            $rCompetent = $_POST['rCompetent'][$i];
        }
        for ($i=0; $i<count($_POST['rAccom']); $i++){
            $rAccom = $_POST['rAccom'][$i];
        }
        mysqli_query($conn,"INSERT INTO qpanswer
                (studentId,personnelId,courteous,prompt,competent,accommodating) 
                VALUES ('$userId','$personnelId','$rCourteous','$rPrompt','$rCompetent','$rAccom')");
    }
    header('location:studentDashboard.php');
?>

【问题讨论】:

标签: php mysqli


【解决方案1】:

您不需要所有内部循环,只需从外部循环获取索引并将其用于所有内部数组。所以这里从foreach键中获取$i...

foreach($_POST['nPersonnelId'] as $i => $personnelId ){
    $rCourteous = $_POST['rCourteous'][$i];

其他字段相同。

正如所指出的 - 使用准备好的语句。

【讨论】:

  • 对不起我只是个初学者``` foreach($_POST['nPersonnelId'] as $i => $personnelId ){ $rCourteous = $_POST['rCourteous'][$i] ; mysqli_query($conn,"INSERT INTO qpanswer (studentId,personnelId,courteous) VALUES ('$userId','$personnelId','$rCourteous'"); } ``` 我按照你说的做了,但什么也没发生我的数据库。我只是礼貌地对其进行了测试
  • 正如它所说的 其他每个字段都相同。 因此,对于循环中的每个字段,您还需要将其更改为类似于 $rCourteous 的方式设置。
  • 对不起,我不明白。你能解释一下我有点慢。很抱歉
猜你喜欢
  • 1970-01-01
  • 2011-09-08
  • 2012-05-11
  • 1970-01-01
  • 2023-03-15
  • 1970-01-01
  • 2021-01-23
  • 2016-06-11
  • 1970-01-01
相关资源
最近更新 更多