PHP - 表单提交时所选复选框的循环数

时间:2013-12-19 15:04:22

标签: php forms

我有一个问题,我需要在表单提交上循环复选框的数量。循环的Foreach复选框我需要然后将数据插入数据库。 我将如何循环遍历通过表单提交传递的复选框数量?

我的代码如下:

形式:

<form action="createChallenge.php" method="post" name="chalCreate">
    Challenge Name:<input type="text" name="chalName" />
    <br />
    Challenge Target:<input type="text"  name="chalTarget"/>
    <br />
    End Date:<input type="text" name="chalDate">
    <br />
    <!-- Needs a jquery datepicker -->
    Select Friends: <br />
    <?php
       $selFriend = $conn->prepare("SELECT * FROM Friends WHERE UserID = '$userID' AND Friend = 'y' ORDER BY FriendName ASC");
       $selFriend->execute();
       foreach($selFriend as $row){
    ?>
    <input type="checkbox" name="test" value="<?php echo $row['FriendID'] ?>"><?php echo $row['FriendName'] ?><br>
    <?php
    }
    ?>

<br />
<button type="submit">Create Challenge</button>
</form>

PHP来处理表单:

<?php
        if(isset($_POST['test']))
        {
            $i = 0;
            foreach($_POST['test'] as $checked)
            {
                echo $friend = $checked;
                $i++;
            }


            echo $name = $_POST['chalName'];
            echo $target = $_POST['chalTarget'];
            echo $date = $_POST['chalDate'];
            echo $friend = $_POST['test'];
            echo $setby = $_COOKIE['userID'];

            $create = $conn->prepare("INSERT INTO Challenge ( chalSetBy, chalName, chalTarget, chalDate ) VALUES ('$setby', '$name', '$target', '$date') ");
            $create->execute();

            if($create)
            {
                echo "Challenge made successfully";
            }
            else
            {
                echo "There was a problem";
            }
        }
      ?>

我认为执行以下操作会回显数据,但事实并非如此,它只选择了最后一个复选框:

$i = 0;
foreach($_POST['test'] as $checked)
{
    echo $friend = $checked;
    $i++;
}

1 个答案:

答案 0 :(得分:1)

在HTML页面中创建一个复选框数组,如下所示,

<form name="frm" method="post">
<input type="checkbox" value="1" name="test[]">
<input type="checkbox" value="2" name="test[]">
<input type="checkbox" value="3" name="test[]">
<input type="checkbox" value="4" name="test[]">
<input type="checkbox" value="5" name="test[]">
<input type="checkbox" value="6" name="test[]">
<input type="submit">
</form>

<?php 
foreach($_POST['test'] as $key=>$value)
{
echo $value."<br>";

}