2

So basically I have the user enter a number on my first screen. Here is test1.php which generates the number of text boxes that the user had previously entered. That number is $input

echo "<form action='test2.php' method='post'>";
for($i=1; $i<=$input; $i++)
{
     echo "Entry $i";
     echo "<input type='text' name='Names'>";
}
echo "<input type='submit' class='button' name='submit' value='submit'>";
echo "</form>";

Then my test2.php should print all the values entered, but it only prints out the last value entered from test1.php. For example is $input is 4, only the text entered in the 4th text box prints, which is understandable as I don't know how to print all values.

$names=$_POST['Names'];
foreach($number as $num){
       echo $num;
}

Is the problem with the name I gave to the textboxes, or something else? Any help is much appreciated.

3 Answers 3

2

Just create a name grouping attribute, so that you'll get an array of inputs instead of just one:

<input type='text' name='Names[]'>
                           // ^ this is important

Sidenote:

I don't know if this is a typo, but this should be $names instead of $number:

$names = $_POST['Names'];
foreach($names as $num){
       echo $num . '<br/>';
}

Sample Demo

Sign up to request clarification or add additional context in comments.

1 Comment

@MattScottGibbs sure no prob, glad this helped
0

Your problem is that you give the same name to all of your input (in your test1.php) so when you try to restore them on your test2.php, your $_POST['Names'] just takes the last input with this name.

A solution is to give a different name to all of your input

In yout first file use it :

echo "<form action='test2.php' method='post'>";
for($i=1; $i<=$input; $i++)
{
    echo "Entry $i";
    echo "<input type='text' name='".$i."'>";
}
echo "<input type='hidden' name='input' value='".$input."'>";
echo "<input type='submit' class='button' name='submit' value='submit'>";
echo "</form>";

And in your 2nd file :

for($i=1; $i<=$_POST['input']; $i++){
    echo $_POST['$i'];
}

1 Comment

Using an integer as id/name is not a good idea, at least prepend some string
0
<form method="post" name="myform">
<input type="text" name="array[]" Value="101"/>
<input type="text" name="array[]" Value="102"/>
<input type="text" name="array[]" Value="103"/>
<input type="text" name="array[]" Value="104"/>
<input type="submit" name="submit" Value="submit"/>
</form>



if(isset($_POST['submit'])){

foreach($_POST['array'] as $myarray) {

    echo $myarray.'<br>';

}

OUTPUT

101
102
103
104

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.