1

I am currently working on a evaluation system. The questions are dynamically created/

So I already tried insert values from different foreach of input fields I use input type text instead of radio button. my code is just inserting the last value get from each foreach loop.

 <?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');
?>
Jasper
  • 41
  • 6

1 Answers1

1

You don't need all of the inner loops, just get the index from the outer loop and use that for all of the inner arrays. So here get $i from the foreach key...

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

Same for each of the other fields.

Also as pointed out - use prepared statements.

Nigel Ren
  • 56,122
  • 11
  • 43
  • 55
  • sorry I'm just a beginner ``` foreach($_POST['nPersonnelId'] as $i => $personnelId ){ $rCourteous = $_POST['rCourteous'][$i]; mysqli_query($conn,"INSERT INTO qpanswer (studentId,personnelId,courteous) VALUES ('$userId','$personnelId','$rCourteous'"); } ``` I did what you told but nothing happens insert nothing in my database. I tested it out with courteous only – Jasper May 25 '19 at 17:11
  • As it says *Same for each of the other fields.* so for each field in a loop you have you need to also change it to similar to the way `$rCourteous` is set. – Nigel Ren May 25 '19 at 17:12
  • sorry I don't get it. Can you please explain it to me I am a little bit slow. Sorry for that – Jasper May 25 '19 at 17:18