Reputation: 1
I'm looping a question for the user with different numerical values for $i. They will input a quantity in the html form that is also looped. Upon them clicking submit, I would like to have an array (with the key ranging form [0] onwards) that stores their response to each particular variant of the question. However, with the code I have written, I only manage to store their last input with the key [0] as if it was the first element of the array. All the previous answers seem to be lost when I call print_r. Please, I would really appreciate it if anyone could point out why this is happening or how I could fix it.
<?php
for ($i=2; $i<=10; $i++)
{
print "question $i";
echo"<form action=\"mysqlranked.php\" method=\"post\">
<input type=\"text\" name=\"pools[]\" value=\"0\" maxlength=\"2\" size=\"2\">
</form>
<br>";
}
print "
<form>
<input type=\"submit\" name=\"formSubmit\" value=\"Submit\">
</form>";
if (isset($_POST["formSubmit"]))
{
$var = $_POST["pools"];
}
print_r($var);
?>
Upvotes: 0
Views: 746
Reputation: 35265
You should not have a new form
tag for every question.
Try the code below:
<form action="mysqlranked.php" method="post">
<?php
for ($i = 2; $i <= 10; $i++)
{
print "question $i";
?>
<input type="text" name="pools[]" value="0" maxlength="2" size="2">
<?php
}
?>
<input type="submit" name="formSubmit" value="Submit">
</form>
<?php
if (isset($_POST["formSubmit"]))
{
$var = $_POST["pools"];
}
print_r($var);
?>
Upvotes: 1
Reputation: 3634
<?php
for ($i=2; $i<=10; $i++)
{
print "question $i";
echo"<form action=\"mysqlranked.php\" method=\"post\">
<input type=\"text\" name=\"pools[]\" value=\"0\" maxlength=\"2\" size=\"2\">
<br>";
}
print "
<input type=\"submit\" name=\"formSubmit\" value=\"Submit\">
</form>";
if (isset($_POST["formSubmit"]))
{
for($counter=0;$counter<count($_POST["pools"]);$counter++)
{
$var = $_POST['pools'][$counter]
}
}
print_r($var);
?>
Upvotes: 0
Reputation: 17362
You had each of your inputs in a new form and the submit button in its own form as well. I fixed it for you:
<?php
echo "<form action=\"mysqlranked.php\" method=\"post\">";
for ($i=2; $i<=10; $i++)
{
print "question $i";
echo"
<input type=\"text\" name=\"pools[]\" value=\"0\" maxlength=\"2\" size=\"2\">
<br>";
}
print "
<input type=\"submit\" name=\"formSubmit\" value=\"Submit\">
";
echo "</form>";
if (isset($_POST["formSubmit"]))
{
$var = $_POST["pools"];
}
print_r($var);
?>
Let me know if it works.
Upvotes: 1