Ali Shahid Ali Shahid - 5 months ago 12
PHP Question

How to select values out of radio buttons and put them in a PHP Variable

I'm making a Quiz. And with each question I'm showing the possible answers( "True" or "False") with a While loop in PHP:

echo "<form method='post' action='quizCheck.php'>";
while(x=0;x<=10; x++){
echo "<div class='buttons'>
<label>True
<input type='radio' name='answer' value='true' />
</label>
<label>False
<input type='radio' name='answer' value='false' />
</label>
</div>";
}
echo "</form>";


Let's say there are 10 questions and I select "True" on 6 questions.

What code do I have to put in quizCheck.php so it can count the number of "True" answers and store it in a variable?

Answer

You will need to do two things, first you need a submit button in the form:

<button type="submit" value="Submit">Submit</button>

Then you will also need the names of the radio inputs to be unique so in the while loop (which you really should just change to a for loop) do:

for(x=0;x<=10; x++){
      echo "<div class='buttons'>
                <label>True
                    <input type='radio' name='answer{$x}' value='true' />
                </label> 
                <label>False
                    <input type='radio' name='answer{$x}' value='false' />
                </label>
             </div>";
}

When the form is submitted, then in quizCheck.php you just check $_POST[answer0] through $_POST[answer9] to see which are true and increment a counter.

If you want the answers in a single array then do this:

for(x=0;x<=10; x++){
      echo "<div class='buttons'>
                <label>True
                    <input type='radio' name='answers[$x]' value='true' />
                </label> 
                <label>False
                    <input type='radio' name='answers[$x]' value='false' />
                </label>
             </div>";
}

When this form is submitted, then in quizCheck.php you just get something like $answers = $_POST[answers] and then go through answers[0] to answers[9] for example