Processing radio buttons in loop in PHP

霸气de小男生 提交于 2020-01-25 05:03:36

问题


I have a loop that iterates 3 times. Inside the loop I have a HTML form that has radio buttons. I'm processing the input using PHP. When I echo the form data, its not showing the correct values. Is it a wrong way of processing the data ? Any help is appreciated.

test.php

<?php
for ($i = 1; $i <= 3; $i++) {
    ?>

    <form action = 'test.php' method = 'post'>
        <input type="radio" name="num<?php echo $i; ?>" value="one">One<br>
        <input type="radio" name="num<?php echo $i; ?>" value="two">Two
    </form>

    <?php
}
?>

<input type = 'submit' value = 'Go'>

<?php
for ($i = 1; $i <= 3; $i++) {
    echo $_POST['num' . $i];
}
?>

回答1:


Move your form outside of your for loop. You are currently creating three forms with one submit button (which isn't attached to any of them).

try this way

<form action = 'test.php' method = 'post'>
<?php
for ($i = 1; $i <= 3; $i++) {
?>
    <input type="radio" name="num<?php echo $i; ?>" value="one">One<br>
    <input type="radio" name="num<?php echo $i; ?>" value="two">Two
<?php
}
?>

<input type = 'submit' value = 'Go'>
</form>

<?php
for ($i = 1; $i <= 3; $i++) {
    echo $_POST['num' . $i];
}
?>



回答2:


use following code: Or you can use radiogroup array it is easier than this.

<form action = 'test.php' method = 'post'>
<?php
for ($i = 1; $i <= 3; $i++) {
?>
<input type="radio" name="num<?php echo $i; ?>" value="one">One<br>
    <input type="radio" name="num<?php echo $i; ?>" value="two">Two
<?php
}
?>
<input type = 'submit' value = 'Go'>
</form>


<?php
for ($i = 1; $i <= 3; $i++) {
echo $_POST['num' . $i];
}
?>



回答3:


@Cagy79 added additional submit buttons.. I have revised the code,

<form action ="" method='post'>
<?php
for ($i = 1; $i <= 3; $i++) {
    ?>
        <input type="radio" name="num<?php echo $i; ?>" value="one">One<br>
        <input type="radio" name="num<?php echo $i; ?>" value="two">Two    

    <?php
}
?>
<input type = 'submit' value = 'Go'>
</form>


<?php
for ($i = 1; $i <= 3; $i++) {
    echo $_POST['num' . $i];
}
?>

This works. :)




回答4:


You have 3 forms without a submit button (it needs to be in between the tags). You need to create one form with one submit button like this so all your data is posted to $_POST.

<form method='post'>
<?php
for ($i = 1; $i <= 3; $i++) {
    ?>
        <input type="radio" name="num<?php echo $i; ?>" value="one">One<br>
        <input type="radio" name="num<?php echo $i; ?>" value="two">Two
    <?php
}
?>
<input type = 'submit' value = 'Go'>
</form>

<?php
for ($i = 1; $i <= 3; $i++) {
    echo $_POST['num' . $i];
}
?>


来源:https://stackoverflow.com/questions/22963930/processing-radio-buttons-in-loop-in-php

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!