简体   繁体   中英

How to get values of multiple selected (dynamic) checkbox in php?

I'm a beginner.I have displayed student id and student name of 10 students on a table. Against each student id, there should be a checkbox (dynamic). When I click the ADD button , all the checked students details (id,name) must be inserted into another database table . What should i do?

Use checkbox name as an array, example :

<form method="post" action="" id="frm_id">
        <input type="checkbox" name="chkid[]" value="10,Anu" />Anu
        <input type="checkbox" name="chkid[]" value="11,Raj" />Raj
        <input type="checkbox" name="chkid[]" value="12,Ram" />Ram
        <input type="checkbox" name="chkid[]" value="13,xxx" />xxx
        <input type="checkbox" name="chkid[]" value="14,yyy" />yyyy
        <input type="checkbox" name="chkid[]" value="15,zzz" />zzz
        <input type="checkbox" name="chkid[]" value="16,qqqq" />qqqq
        <input type="submit" value="Insert"  name="sub"/>
        </form>
        <?php
        if(isset($_POST['sub']))
        {
        $id=$_POST['chkid'];
        for($i=0;$i<count($id);$i++)
        {
        $exp=explode(',',$id[$i]);//Explode id and name
        echo 'id='.$exp[0].',Name='.$exp[1];echo "<br>";
        echo $query="INSERT INTO tbl_student (id,name) values ('$exp[0]','$exp[1]')";echo "<br><br>";
        }
        }
        ?>
<form method="post" action="pageurl">
        <input type="checkbox" name="studentid[]" value="1,Student1" />Student1
        <input type="checkbox" name="studentid[]" value="2,Student2" />Student2
        <input type="checkbox" name="studentid[]" value="3,Student3" />Student3
        <input type="checkbox" name="studentid[]" value="4,Student4" />Student4

        <input type="submit" />
        </form>
        <?php

        $id=$_POST['studentid'];
        foreach($id as $student)
        {
        $extract = explode(',',$student);
        $query="INSERT INTO student (id,name) values ('$extract[0]','$extract[1]')";
        }

        ?>

try using the array of checkbox element like this:

<input type="checkbox" name="months[]" value="feb">February<br>
<input type="checkbox" name="months[]" value="mar">March<br>
<input type="checkbox" name="months[]" value="apr">April<br>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM