Forum Moderators: coopster
I am trying to create a script that will echo an amount of forms, according to a users input. For this, I am using two pages - submit.php and output.php.
In submit.php I have an echo statement and a counter. I appended the counter value onto the form field names so I have a unique name for every field, this part works ok.
<?php
echo '<form method="post" action="output.php"><br>';
for ($i=0, $j=0; $i<=2; $i++, $j++)
{
echo 'Town: Post Code: <br />
<input name="town' . $j . '" type="text" /><input name="code' . $j . '" type="text" /><br /><br />';
}
echo '<input type="submit" /><br /></form>';
?>
However, I can't get output.php to echo the correct amount of unique statments, without hardcoding an echo for every variable. Which kind of defeats the purpose of having a user defined amount.
I can get the same amount by using the same counter variable that would be set by the user but I can't get the unique field name the same way.
i.e. $town . $i or $_REQUEST['town'] . $i
In other words, something like this doesn't work in output.php
<?php
for ($i=0, $j=0; $i<=2; $i++, $j++)
{
echo 'The postcode for ' . $_REQUEST['town'] . $i . ' is ' . $_REQUEST['code'] . $j . ' Now you know!');<br />';
}
?>
All I get back is the value of $i and $j instead of the value for town0, town1, town2 and code0, code1, code2.
Obviously I am messing this up big time and I'm not asking anyone to write it for me, I would just like someone to point me in the right direction of the method I should be using.
Thanks in advance!
<input [b]name="town[]"[/b] type="text" /><input [b]name="code[]"[/b] type="text" /><br /><br />';
And on output.php type the following just to view the results:
echo '<pre>';
print_r($_POST['town']);
print_r($_POST['code']);
echo '</pre>';
This puts everything in an array for you instead of you having to use variable variables. Let me know how this works for you :)
$_POST['code'][$index]
I hope this is enough to get you started. If you need any more help don't hesitate to ask ;)
I have it cracked! New code for submit.php:
<?php
echo '<form method="post" action="output.php"><br>';
for ($i=0; $i<=2; $i++)
{
echo 'Town: Post Code: <br />
<input name="town[]" type="text" /><input name="code[]" type="text" /><br /><br />';
}
echo '<input type="submit" /><br /></form>';
?>
Code for output.php:
<?php
for ($i=0; $i<sizeof($town); $i++)
{
echo 'The postcode for ' . $_POST['town'][$i] . ' is ' . $_POST['code'][$i] . ' Now you know!<br />';
}
?>
Thanks very much for your help, I understand this procedure a lot better now.
jatar_k,
Thank you for that advice. It has been duly noted and taken on board.