vendredi 1 mai 2020

PHP Quiz Radio and Checkbox Calculation

I'm designing a simple quiz with PHP and would like to know if i'm approaching it the correct way before proceeding.

The quiz will have approximately 25 questions, a mixture of radio buttons and checkboxes. The idea is to calculate the total and display this to the user when the quiz is submitted.

I have just four questions so far. Questions 1 - 3 are radio buttons, one selection max. Question 4 is a checkbox and allows two selections max, each correct selection is worth 0.5

Here's a snippet of my html code (question and answer text removed).

HTML

// q1 answer is value 2
<input type="radio" name="form[1-1]" value="1">
<input type="radio" name="form[1-1]" value="2">
<input type="radio" name="form[1-1]" value="3">

// q2 answer is value 1
<input type="radio" name="form[1-2]" value="1">
<input type="radio" name="form[1-2]" value="2">
<input type="radio" name="form[1-2]" value="3">

// q1 answer is value 2
<input type="radio" name="form[1-3]" value="1">
<input type="radio" name="form[1-3]" value="2">
<input type="radio" name="form[1-3]" value="3">

// q4 answer is value 1 or 3. 0.5 points each
<input type="checkbox" name="form[1-4][]" value="1">
<input type="checkbox" name="form[1-4][]" value="2">
<input type="checkbox" name="form[1-4][]" value="3">
<input type="checkbox" name="form[1-4][]" value="4">

The PHP code below works, is it the correct approach or is there a more efficient way? Specifically with the checkbox question 4.

PHP

$total = array();

$total = '0';

$q1 = $_POST['form']['1-1'];
$q2 = $_POST['form']['1-2'];
$q3 = $_POST['form']['1-3'];
$q4 = $_POST['form']['1-4'];

// answer with value 2 is correct
if ($q1 == '2' ) {
    $total++;
};
// answer with value 1 is correct
if ($q2 == '1' ) {
    $total++;
};
// answer with value 2 is correct
if ($q3 == '2' ) {
    $total++;
};
// answer with value 1 is correct
if ($q4[0] == '1' ) {
    $total = $total + 0.5;
};
// answer with value 3 is correct
if ($q4[1] == '3' ) {
    $total = $total + 0.5;
};

// send $total to database here

I'm not looking to use JS / Jquery, I want to use a PHP approach.

Aucun commentaire:

Enregistrer un commentaire