I have an input form that allows me to insert a new quiz into a database. The form looks something like this:
Question Title
Question #1
is_correct_1
choice#1
is_correct_2
choice#2
is_correct_3
choice#3
is_correct_4
choice#4
Question #2
.
.
.
Different quizzes will having varying amounts of questions (although each question will always have 4 possibilities). I determine how many questions it will have before the form is constructed. In order to accomplish this I generate the form using a couple for loops. I also initialize the names of different input fields in the same manner. See below:
// Grab number of questions from Admin page
$num_of_Qs = $_POST['num_of_Qs'];
// Produce form by using for loops
echo '<form method="post" action="' . $_SERVER['PHP_SELF'] . '">';
echo '<fieldset><legend>New Quiz Details</legend><label for="title">Quiz Title</label>';
echo '<input type="text" id="title" name="title" value="" /><br /><br />';
for ($i = 1; $i <= $num_of_Qs; $i++) {
echo '<label for="question_'.$i.'">Question #'.$i.'</label>';
echo '<input type="text" id="question_'.$i.'" name="question_'.$i.'" value="" /><br /><br />';
for ($x = 1; $x <= 4; $x++) {
echo '<label for="is_correct_'.$i.'_'.$x.'">is_correct_'.$x.'</label>';
echo '<input type="text" id="is_correct_'.$i.'_'.$x.'" name="is_correct_'.$i.'_'.$x.'" value="" /><br />';
echo '<label for="choice_'.$i.'_'.$x.'">Choice #'.$x.'</label>';
echo '<input type="text" id="choice_'.$i.'_'.$x.'" name="choice_'.$i.'_'.$x.'" value="" /><br /><br />';
}
}
echo '</fieldset><input type="hidden" name="num_of_Qs" value="'.$num_of_Qs.'" />';
echo '<input type="submit" value="Create" name="create" /></form>';
So, the variables end up looking something like this:
$title
$question_1
is_correct_1_1
choice_1_1 // first question, first choice
is_correct_1_2
choice_1_2 // first question, second choice
...
When I go to store those variables by grabbing it using the $_POST function, I'm having trouble. Here is my code:
// If user has submitted New Quiz data
if (isset($_POST['create'])) {
$num_of_Qs = $_POST['num_of_Qs'];
$title = $_POST['title'];
for ($i = 1; $i <= $num_of_Qs; $i++) {
$question_$i = $_POST['question_'.$i.''];
for ($x = 1; $x <= 4; $x++) {
$is_correct_$i_$x = $_POST['is_correct_'.$i.'_'.$x''];
$choice_$i_$x = $_POST['choice_'.$i.'_'.$x.''];
}
}
print_r($title);
print_r($question_1);
exit();
}
I'm wondering if there is a way to grab the values from the form based on the structure I have determined for my variable names. The specific problem lies in $question_$i = .... Can I salvage this code or do I need to rethink the way I am naming these variables? Thanks!