Insert foreach checkbox checked

I like to insert into mysql table, rows selected on the form table using checkboxes.

When I select the first row downwards, everything is okay BUT when I select others than the first row, no data inserted. The script is forcing me to select row 1.

I want only select checkboxes inserted into the database.

Below is my table:

<table id="simple-table" class="table table-striped table-condensed responsive">
         <th style="width:5%" class="center">
          <label class="pos-rel">
           <input type="checkbox" name="offerring" class="ace" />
           <span class="lbl"></span>
   <th style="width:32%">Student Name</th>
   <th style="width:10%">Adm. No</th>
   <th style="width:10%" class="center">CA1 (10%)</th>
   <th style="width:10%" class="center">CA2 (10%)</th>
   <th style="width:10%" class="center">CA3 (10%)</th>
   <th style="width:10%" class="center">Exam (70%)</th>
   <th style="width:10%" class="center">Total (100%)</th>
   <th style="width:3%" class="hidden">ID</th>



        $session = clean($_POST["session"]);
        $term = clean($_POST["term"]);
        $c_taught = clean($_POST["c_taught"]);
        $s_taught = clean($_POST["s_taught"]);
        $process_limit = clean($_POST["process_limit"]);
        $session_phrase = "Session";

        $sql = "SELECT `id`, `StudentID`, `StudentName` FROM tbl_students WHERE `StudentClass` = '".$c_taught."' ORDER BY `StudentName` ";

        $result = $conn->query($sql);
        if ($result->num_rows > 0) {
                                                // output data of each row
            while($row = $result->fetch_assoc()) { 
             $id = $row['id']; 
             $student_name = $row['StudentName'];
             $student_id = $row['StudentID'];
                 <td class="center">
                  <label class="pos-rel">
                   <input type="checkbox" class="ace" name="checked[]" value="<?php echo $row['id'];?>" />
                   <span class="lbl"></span>
           <td><?php echo $student_name; ?><input type="hidden" name="student_name[]" value="<?php echo $row['StudentName']; ?>"/></td>
           <td><?php echo $student_id; ?><input type="hidden" name="student_id[]" value="<?php echo $row['StudentID']; ?>"/></td>
           <td class="center"><?php echo '<input type="text" maxlength="2" size="6" name="CA1[]" autofocus>'; ?></td>
           <td class="center"><?php echo '<input type="text" maxlength="2" size="6" name="CA2[]">'; ?></td>
           <td class="center"><?php echo '<input type="text" maxlength="2" size="6" name="CA3[]">'; ?></td>
           <td class="center"><?php echo '<input type="text" maxlength="2" size="6" name="Exam[]">'; ?></td>
           <td class="center"><?php echo '<input type="text" maxlength="2" size="6" name="Total[]">'; ?></td>
           <td class="hidden"><?php echo '<input type="hidden" name="id[]" value="'.$row["id"].'">'; ?></td>                
       <?php $cnt=$cnt+1;}}
       else {
        $msg = "<span class='red'><h4> No data available for your selection. </h4></span>";  



Open in new window

And my Script (on the same page with form):

$enroll_sql = "";
//Assessment Entry
if(isset($_POST['add_assessment'])) {

        echo '<script>alertify.alert("No Student is selected.",function(e){if(e){document.location.href = "cass_entry.php";}}).set("labels", {ok:"OK!"}).set("defaultFocus", "ok").set("title", "Assessment")


    foreach($_POST['checked'] as $id=>$value) {
        $session = $_POST['session'];
        $term = $_POST['term'];
        $c_taught = $_POST['c_taught'];
        $s_taught = $_POST['s_taught'];
        $student_id = $_POST['student_id'][$id];
        $student_name = $_POST['student_name'][$id];
        $ca_1 = $_POST['CA1'][$id];
        $ca_2 = $_POST['CA2'][$id];
        $ca_3 = $_POST['CA3'][$id];
        $exam = $_POST['Exam'][$id];
        $total = $_POST['Total'][$id];
        $enroll_sql = '
        INSERT INTO tbl_subjects_enrollment (`Session`,`Term`,`Student_Class`,`Subject_Name`,`Student_ID`,`Student_Name`,`CA_1`,`CA_2`,`CA_3`,`Exam`,`Total`) 
        VALUES("'.$session.'", "'.$term.'", "'.$c_taught.'", "'.$s_taught.'", "'.$student_id.'", "'.$student_name.'", "'.$ca_1.'", "'.$ca_2.'", "'.$ca_3.'", "'.$exam.'", "'.$total.'")';

        echo $enroll_sql;

        if (mysqli_query($conn, $enroll_sql)) {
            $success_msg = '<div class="alert alert-success">
            <button type="button" class="close" data-dismiss="alert">
            <i class="ace-icon fa fa-times"></i>
            <h4><i class="ace-icon fa fa-check"> Success</i></h4>
            <p>Assessment scores were successfully saved.</p></div>';

        } else {
            echo "Error saving Assessment: " . $conn->error;

Open in new window

What am I doing wrong, please?
Opeyemi AbdulRasheedAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Chris StanyonWebDevCommented:
The problem you have is becuase you're not indexing your check box. A check box is only sent to the server if it's checked, so if you check 3 boxes for example, they will have the index of 0, 1, 2, and these will have no bearing on your actual student arrays. So check[0] might actually be on the row for student 5.

You would be better off indexing your checked option with the student id:

<input type="checkbox" name="checked[<?= $student_id ?>] ...

In fact, if you index all your fields:

<input type="text" name="student[<?= $student_id ?>]['name']
<input type="text" name="student[<?= $student_id ?>]['CA1']
<input type="text" name="student[<?= $student_id?>]['CA2'],

Then in you PHP you can simply to:

foreach ($_POST['checked'] as $id):
    $student = $_POST['student'][$id];
    // access  the values
    $name = $student['name'];
    $ca1 = $student['CA1'];
    $ca2 = $student['CA2'];

Open in new window

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Opeyemi AbdulRasheedAuthor Commented:
@Chris Stanyon, exactly what I did. I'm so grateful. You're the best. I like it here.
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today

From novice to tech pro — start learning today.