Jump to content

Radio Inputs and PHP


Zakhary

Recommended Posts

I got problems with radio inputs and PHP. I make a quiz and I set 4 optional answers each question. To make inputs not multi select able I gotta set their names the same. Unfortunately, PHP reads them by names and it makes PHP fail. How can I avoid it? I set optional number 1-4 for each answer. My example website and code: http://tourney.adrenalinex.co.uk/max-o-meter/index.php

 

<form action="quiz_script.php" method="post">

1. Question number one:<br />

<input type="radio" name="q1_a1" value="q1_a1" /> Answer 1<br />
<input type="radio" name="q1_a2" value="q1_a2" /> Answer 2<br />
<input type="radio" name="q1_a3" value="q1_a3" /> Answer 3<br />
<input type="radio" name="q1_a4" value="q1_a4" /> Answer 4<br /><br />


<center><input type="submit" value="I want to check the answers!" class="submit" /></center>

</form>

 

<?php

$q1_a1 = $_POST['q1_a1'];
$q1_a2 = $_POST['q1_a2'];
$q1_a3 = $_POST['q1_a3'];
$q1_a4 = $_POST['q1_a4'];

$score = 0;

if ($selected_radio = $q1_a1) {
$score = $score+4;
} else if ($selected_radio = $q1_a2) {
$score = $score+3;
} else if ($selected_radio = $q1_a3) {
$score = $score+2;
} else if ($selected_radio = $q1_a4) {
$score = $score+1;
}

echo $score;

?>

Link to comment
Share on other sites

Give each questions radio buttons the same name value, e.g. "q1", these are then grouped together as one input  Then in the PHP just retrieve that input and check it against an array of list of variables containing the correct answers.

 

$answer = $_POST['q1'];

if($answer == $q1_answer){
     $score += 1;
}

 

Hope this helps. Sorry if there is something wrong with the code. Done this on my phone

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.