mysql - Using for() loop to create unique PHP variables -
i have input form allows me insert new quiz database. form looks 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 having varying amounts of questions (although each question have 4 possibilities). determine how many questions have before form constructed. in order accomplish generate form using couple loops. initialize names of different input fields in same manner. see below:
// grab number of questions admin page $num_of_qs = $_post['num_of_qs']; // produce form using 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 />'; ($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 />'; ($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, variables end looking 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 go store variables grabbing using $_post function, i'm having trouble. here code:
// if user has submitted new quiz data if (isset($_post['create'])) { $num_of_qs = $_post['num_of_qs']; $title = $_post['title']; ($i = 1; $i <= $num_of_qs; $i++) { $question_$i = $_post['question_'.$i.'']; ($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 way grab values form based on structure have determined variable names. specific problem lies in $question_$i = ...
. can salvage code or need rethink way naming these variables? thanks!
to answer question, can reference variables strings like
$var_1 = "hello"; echo ${"var_1"}; // or $str = "var_1"; echo $$str;
but don't that
you want store these values in array.
$question[$i] = $_post['...']; $is_correct[$i][$x] = $_post['...'];
Comments
Post a Comment