I want to know how to handle multiple inputs from a form with multiple atributes.
This code generates my fields:
<form method="POST" action="test5.php" id="1">
<?
if($_SESSION["peoplecount"] != 0){
for ($i = 0; $i <= $_SESSION["peoplecount"]; $i++) {
echo ' Name<input type="text" name="'.$i.'"> Adult<input type="radio" name="'.$i.'" value="adult" /> Minor<input type="radio" name="'.$i.'" value="minor" /> <br/>';
} }
?>
<input class="button" type="submit" value="I/We Agree" style="width:200px;"/>
</form>
once submitted — or test5.php as its mentioned in the “action” part,
foreach ($_POST as $key => $value) {
print "{$key}: {$value}<br />";
}
and the output is
0: adult
1: adult
2: adult
3: adult
Notice it has 0, 1, 2… and then adult. It does not even mention the name of the person from the text input.
I can alter the form to:
</blockquote>
<form method="POST" action="test5.php" id="1">
<?
if($_SESSION["peoplecount"] != 0){
for ($i = 0; $i <= $_SESSION["peoplecount"]; $i++) {
echo ' Name<input type="text" name="usersname" id="usersname"> Adult<input type="radio" name="age" value="adult" id="age"/> Minor<input type="radio" name="age" value="minor" id="age"/> <br/>';
} }
?>
<input class="button" type="submit" value="I/We Agree" style="width:200px;"/>
</form>
Using the same test5.php, I get
usersname:
age: adult
The value of the age is not posted and the the foreach loop in test5.php ends, hence the line return, before it completly runs through one complete post.
I hope I did a good enough job explaining.
I want my output to be:
SomeName Adult
SomeOtherName Minor
….
Your problem is that you are creating two form inputs with
name='$i', and the second one (the radio button) is overwriting the first. I would suggest instead that you use a string including$ito build the name attributes:Now your
$_POSTarray will look like:An even better way to handle it is to use arrays as form name attributes with
[](Note I’ve switched to double-quotes here, to avoid all the extra concatenation and complicated quoting.)In this case, your
$_POSTlooks like:To access them, you can use a
foreachloop like so: