如何在插入中插入多个动态复选框值?

时间:2017-12-07 07:48:44

标签: php multidimensional-array

当我插入此表单时,所有字段都插入但问题是多个复选框值不插入?

这是我的HTML代码:

<form method="post" action="<?php echo $_SERVER['PHP_SELF'] ?>">    

    <?php
        $j=3;

        for($i=0;$i< $j; $i++)
        {
            ?>
            First name :: <input name="firstname[]" type="text" value=""/><br>
            <input name="loop" type="hidden" value="<?php echo $j ?>"/>
            Last name :: <input name="lastname[]" type="text" value="" /><br>
            Age :: <input name="age[]" type="text" value="" /><br>
            <input name="hobbey[]" type="checkbox" value="Cricket" />Cricket
            <input name="hobbey[]" type="checkbox" value="Football" />Football
            <input name="hobbey[]" type="checkbox" value="Tennis" />Tennis
            <br><br>
            <?php
        }
    ?>

    <input name="btnsubmit" type="submit" value="Submit" />
</form>

</body>
</html>

这是我的PHP代码:

    $query = "insert into register (firstname,lastname,age,hobbey) values";

    for($i=0; $i<$_POST["loop"]; $i++)
    {
        $firstname=$_POST["firstname"][$i];
        $lastname=$_POST["lastname"][$i];
        $age=$_POST["age"][$i];

        $hobbey=$_POST["hobbey"][$i];

        $query .= "('$firstname','$lastname','$age','$hobbey')";
    }

2 个答案:

答案 0 :(得分:0)

在复选框的名称上使用多数组

<input name="hobbey[<?php echo $i;?>][]" type="checkbox" value="Cricket" />Cricket
<input name="hobbey[<?php echo $i;?>][]" type="checkbox" value="Football" />Football
<input name="hobbey[<?php echo $i;?>][]" type="checkbox" value="Tennis" />Tennis

在php中你做:

 $hobbey=implode(';',$_POST["hobbey"][$i]);

注意sql注入

答案 1 :(得分:0)

因为在i = 0的值下你获得了hobbey值的数组,即它不插入,尝试使用implode生成一个数组字符串,然后将该字符串插入到你的表中,

    $hobbey=$_POST["hobbey"][$i];
    $hby=implode(',',$hobbey);
    $query .= "('$firstname','$lastname','$age','$hby')";