Kurt Görg Kurt Görg - 21 days ago 6
HTML Question

Returning values of a few drop down forms made in a loop undefined index error

I have created a HTML form inside a PHP loop but I am having trouble returning the values of the dropdown lists after clicking my submit button. The problem is that it is returning a value for $dropdown0, but not for any other $dropdown. In this example there are 3 questions, so it should be returning $dropdown0, $dropdown1 and $dropdown2, yet when I press submit, it gives an error saying:


Notice: Undefined index: dropdown1 in
C:\xampp\htdocs\website\playQuiz.php on line 54

Notice: Undefined index: dropdown2 in
C:\xampp\htdocs\website\playQuiz.php on line 55


for($x=0; $x<=$noQuestions-1; $x++){
$type = "dropdown".$x;
echo "<table>";
echo "<tr>"."Question ".($x+1).": ".$question[$x]."</tr>";
echo "<form method=\"post\">";
echo "<Select class=\"form-control\" type=\"text\" name=$type required>";
echo "<option value=\"1\">".$optionData[$x][0]."</option>";
echo "<option value=\"2\">".$optionData[$x][1]."</option>";
echo "<option value=\"3\">".$optionData[$x][2]."</option>";
echo "<option value=\"4\">".$optionData[$x][3]."</option>";
echo "</select>";
echo "</form>";
echo "</table>";
}


The code for printing the values of the drop down lists using a button called 'submit':

if (isset($_REQUEST['submit'])){
extract($_REQUEST);

echo $_POST['dropdown0'];
echo $_POST['dropdown1'];
echo $_POST['dropdown2'];
}

Answer

that is because you have built 3 forms inside that loop, so when you click the submit button it sends the first form only, you need to get the form element outside the loop

echo "<form method=\"post\">"; // << here
For($x=0; $x<=$noQuestions-1; $x++){
                $type = "dropdown".$x;
                echo "<table>";
                echo "<tr>"."Question ".($x+1).": ".$question[$x]."</tr>";
                echo "<Select class=\"form-control\" type=\"text\" name=$type required>";
                echo "<option value=\"1\">".$optionData[$x][0]."</option>";
                echo "<option value=\"2\">".$optionData[$x][1]."</option>";
                echo "<option value=\"3\">".$optionData[$x][2]."</option>";
                echo "<option value=\"4\">".$optionData[$x][3]."</option>";
                echo "</select>";

                echo "</table>";
            }
echo "</form>";  // << here