dimanche 22 mars 2020

How to get the result of dynamically created checkboxes into array

I am building a PHP project in which i have few records of students in MySQL database. I am fetching them and creating separate checkboxes for each record. Then, after submitting the above form, I hae the code to get the POST values of all the checkboxes by their unique name attribute and checking if the variable is set. If yes, then it will be added in array. Later, I am printing the size of array and the value of array elements. But, though selecting some records, I am not getting any record as checked and no value in array. This is my code:

$present_array = array();
$year = $_GET['year'];
$date = date("d-m-Y");
if($result = $conn->query("SELECT rollno, name FROM students WHERE year=".$year." ORDER BY rollno ASC")){?>
    <form action="" method="post">
    <?php
    $first = true;
    while($row = $result->fetch_assoc()){
        $rollno = $row['rollno'];
        $name = $row['name'];
        echo '<tr>
                <td class="w3-center" style="width:200px;border:1px solid black;">'.$rollno.'</td> 
                <td class="w3-center" style="width:200px;border:1px solid black;">'.$name.'</td>';?>
                <td class="w3-center" style="width:200px;border:1px solid black;">
                    <input type="checkbox" name="<?php echo $rollno.".chkbox"?>">
                </td>
            </tr>
        <?php
    }
    ?>

    <button type="submit" class="button btn-primary" name="submitbtn">Submit</button>
    </form> 
    <?php
    if(isset($_POST['submitbtn'])){
        while($row = $result->fetch_assoc()){
            $rollno = $_POST[$rollno.".chkbox"];
            if(isset($rollno)){
                array_push($present_array, $rollno);
            }
        }

        echo "size: ".count($present_array);

        for($i=0; $i<count($present_array); $i++){
            echo "arr: ".$present_array[$i];
        }
    }
    $result->free();
}



Aucun commentaire:

Enregistrer un commentaire