I’ve been developing a quiz powered by PHP, jQuery and a database. It works pretty nicely except for questions that ask users to choose several checkboxes.
After selecting some answers, a user clicks the Submit button and the form forwards him to another page, which features the following code:
// This first script is designed to convert the choices for the readio-checkboxes question (#10) into a single letter that can be plugged into the key that follows.
if (isset($_POST))
{
// Check that the 2 correct answers are set, and the 3 incorrect answers are not set
if (isset($_POST['q10-A'], $_POST['q10-B'], $_POST['q10-C']) &&
!isset($_POST['q10-D']) &&
!isset($_POST['q10-E']) &&
!isset($_POST['q10-F']))
{
$Ch = 'A';
}
else
{
$Ch = 'B';
}
}
// Unfortunately, $Ch and variations thereof don't work. If I replace ''.$Ch.'' with 'A', it still doesn't work.
$totalCorrect = 0;
// Note that #2 is a fill-in-the-blank question.
$answers = [1 => 'A', 2 => 'Jupiter', 3 => 'C', 4 => 'D', 5 => 'A', 6 => 'C', 7 => 'C', 8 => 'C', 9 => 'B', 10 => ''.$Ch.''];
foreach ($answers as $num => $answer)
{
$question = 'q'.$num;
if (isset($_POST[$question]) && $_POST[$question] === $answer)
{
$totalCorrect++;
}
}
$pct = round( (($totalCorrect/count($answers)) * 100), 0);
echo $totalCorrect.' correct ('.$pct.'%)';
I have an idea for a workaround. Right now, if a user gets all the questions correct, their score is recorded as 90%, as the last question falls through the cracks. But suppose I change the first script to something like this?:
if (isset($_POST))
{
// Check that the 2 correct answers are set, and the 3 incorrect answers are not set
if (isset($_POST['q10-A'], $_POST['q10-B'], $_POST['q10-C']) &&
!isset($_POST['q10-D']) &&
!isset($_POST['q10-E']) &&
!isset($_POST['q10-F']))
{
$Score = 10;
}
else
{
$Score = 0;
}
}
If the user chooses all three correct check boxes, they get the question right - worth 10 points on a 10-question quiz. So how could you add 10% to the 90% computed by the answer key? I have it set up so the scores are recorded in a database, so I don’t want to short change anyone 10% (or more, if there are additional checkbox questions).