如何允许选择每组单选按钮一次?

时间:2013-05-31 07:04:33

标签: php html radio-button

我已经做了一个while循环来获取我的数据库中的所有问题和答案,但是,我无法通过使用单选按钮为每个问题选择一个答案。

<form class ="formlayout" action = "Test.php" method = "post">
    <?php
    while ($row = mysqli_fetch_assoc($result)) {
        $question = $row['question'];
        $option1 = $row['option1'];
        $option2 = $row['option2'];
        $option3 = $row['option3'];
        ?>

        <?php echo $question ?> <br>
        <input type="radio" name="<?php echo $i ?>" value="$option1"><?php echo $option1 ?><br>
        <input type="radio" name="<?php echo $i ?>" value="$option2"><?php echo $option2 ?><br>
        <input type="radio" name="<?php echo $i ?>" value="$option3"><?php echo $option3 ?><br>
        <?php echo "" ?><br>
        <?php
    }
    ?>
        <input type="submit" value="Submit"/>
</form>

感谢。

3 个答案:

答案 0 :(得分:0)

只需给他们相同的名字:

<form class ="formlayout" action = "Test.php" method = "post">
    <?php
    while ($row = mysqli_fetch_assoc($result)) {
        $question = $row['question'];
        $option1 = $row['option1'];
        $option2 = $row['option2'];
        $option3 = $row['option3'];
        ?>

        <?php echo $question ?> <br>
        <input type="radio" name="YourName" value="$option1"><?php echo $option1 ?><br>
        <input type="radio" name="YourName" value="$option2"><?php echo $option2 ?><br>
        <input type="radio" name="YourName" value="$option3"><?php echo $option3 ?><br>
        <?php echo "" ?><br>
        <?php
    }
    ?>
        <input type="submit" value="Submit"/>
</form>

答案 1 :(得分:0)

我认为$ i未定义,为什么不简单地使用一些静态字符串作为名称.. 例如:

<input type="radio" name="my_radio"/>

答案 2 :(得分:0)

定义你的$i并将其增加为具有不同的答案组,您也可以更改您的电台名称,以便以后轻松解析:

<form class ="formlayout" action = "Test.php" method = "post">
    <?php
    $i = 0;
    while ($row = mysqli_fetch_assoc($result)) {
        $question = $row['question'];
        $option1 = $row['option1'];
        $option2 = $row['option2'];
        $option3 = $row['option3'];
        ?>

        <?php echo $question ?> <br>
        <input type="radio" name="answer_<?php echo $i ?>" value="$option1"><?php echo $option1 ?><br>
        <input type="radio" name="answer_<?php echo $i ?>" value="$option2"><?php echo $option2 ?><br>
        <input type="radio" name="answer_<?php echo $i ?>" value="$option3"><?php echo $option3 ?><br>
        <?php echo "" ?><br>
        <?php
        $i++;
    }
    ?>
        <input type="submit" value="Submit"/>
</form>