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
https://forums.phpfreaks.com/topic/265836-radio-inputs-and-php/
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

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.