Help with &_SESSION needed

I am building a Quiz generator using PHP. The idea is to set up an array with questions and answers and let PHP build most of the required HTML (that way the same code can be reused for many different quizzes).

I am almost there >:( but have trouble with $_SESSION I think.

After the user “submits” answers, PHP gets them via $_POST and the code reloads the quiz with the answers submitted, then display a score message (this last bit not there yet. The problem is that successive “submit” displays the answer selections of the previous “submit”. This can easily be visualized by answering TRUE to all questions, submit, then FALSE to all questions and submit again. Continuing to “submit” will alternate between the set of answers. >:(

The funny thing is that the debugging echos that come to the top of the page actually have the correct answers for the current “submit”.

You can see it all at:
http://www.woodyacresranch.com/Quizzes/Quiz_Handler_FRB.php

Here is the code:

[php]<?php
// Starts the session
session_start();

$process = $_GET['process'];

// Get session variables
for ( $x=0 ; $x<=$qQty ; $x++ ) // $x walks the question sets
{
	for ( $y=0 ; $y<=$sub ; $y++ ) // $y walks the question array
	{
		// The first element in question array is the question title
		if ( $y == 0 ) {$_SESSION["a".$x.$y] = "";}
		else
		{
			// Get the answers for question $x
			$_SESSION["a".$x.$y] = trim($_POST["a".$x.$y]);
		}
	}
}
// Define Quiz questions and load the SESSION answers
$qSet = array(
			array(
				array("Conditions of Participation"), // This is the title of the question
				array("Dogs do not need a tattoo or microchip to compete in French Ring Sport as long as 
						they are registered with a breed affiliation.","1.1.2","B","false",$_SESSION["a01"]),
				array("Members are only allowed to compete with 3 Blue dogs in their lifetime.","1.1.6","B","false",$_SESSION["a02"]),
				array("A female dog in heat must compete after all the other dogs in the trial.","1.1.10","B","true",$_SESSION["a03"]),	
				array("An individual decoying a trial is authorized to compete his or her own dog, 
						as long as the dog is presented by another handler.","1.1.11","B","false",$_SESSION["a04"]),
				),
			array(
				array("The following is needed to hold a trial:"), // This is the title of the question
				array("A judge and a deputy judge.","1.2.6","B","true",$_SESSION["a11"]),
				array("A Ring Steward.","1.2.6","B","false",$_SESSION["a12"]),
				array("A blank revolver or something that make a similar noise.","1.2.6","B","false",$_SESSION["a13"]),
				array("A horn.","1.2.6.","B","true",$_SESSION["a14"]),
				array("A minimum of eight cones or flags.","1.2.6","B","true",$_SESSION["a15"]),
				array("A minimum of eight pieces of food for the Food Refusal exercise.","1.2.6","B","false",$_SESSION["a16"]),
				),
			);

?>

Quizzes <?php include("/home/content/05/8083005/html/header.html"); include("/home/content/05/8083005/html/topbar.html"); include("/home/content/05/8083005/html/sidebar.html"); ?>
<?php include("/home/content/05/8083005/html/_Includes/Kludge.html");?>
French Ring Brevet
Handler Quiz

<?php if ($process == 'check') {echo 'Process is CHECK';}
		// Display the questions
		foreach ( $qSet as $key1 => $q )
		{
			foreach ( $q as $key2 => $value )
			{
				$qNum = $key1 + 1;
				if ($key2 == 0)
				{
					echo "<tr><td colspan='2' align='left' style='font-size:1em;font-weight:bold'>Question ".$qNum."</td></tr>
						  <tr><td colspan='2' align='left' style='font-size:0.85em;font-weight:bold'>".$q[$key2][0]."<br /><br /></td></tr>";
				}
				else
				{
					echo "<tr>
							<td width='120' align='left' valign='top' style='font-size:0.85em'>
								<input type='radio' name='a".$key1.$key2."' value='true'";
									if ($q[$key2][4] == 'true')  {echo "checked='checked'";} echo ">True
								<input type='radio' name='a".$key1.$key2."' value='false'";
									if ($q[$key2][4] == 'false') {echo "checked='checked'";} echo ">False</td>
							<td width='350' align='left' valign='top' style='font-size:0.85em'>".$q[$key2][0]."</td>
						  </tr>
						  <tr><td>&nbsp;</td></tr>";
				}

// echo '$key1 = ‘.$key1.’ / $key2 = '.$key2;
$qQty = $key1;
$qSub[$key1] = $key2;
}
}
// echo ‘
$qQty =’.$qQty;
// Get session variables
// $x walks the $a (answers) array
foreach ( $qSet as $key1 => $q )
{
// $y walks the $sub (sub-questions) array
foreach ( $q as $key2 => $value )
{
// The first array element in $sub is the question’s title
if ( $key2 == 0 ) {$_SESSION[“a”.$x.$y] = “”;} // First element in $q is question title
else
{
// Get the answers for question $key1
$_SESSION[“a”.$key1.$key2] = trim($_POST[“a”.$key1.$key2]);
echo “
a”.$key1.$key2." = ".trim($_POST[“a”.$key1.$key2]);
}
}
}
// session_unset();
// session_destroy();
// If responses just submitted, check answers
if ($process == ‘check’)
{
$aCount = 0; $aGood = 0;
foreach ( $qSet as $key1 => $q )
{
foreach ( $q as $key2 => $value )
{
$qNum = $key1 + 1;
if ($key2 != 0)
{
$aCount = $aCount + 1;
if ( $q[$key2][3] == $q[$key2][4] ) {$aGood = $aGood + 1;}
}
}
}
echo ‘$aCount = ‘.$aCount.’ / $aGood = ‘.$aGood.’
’;
}
?>

[/php]

Please help. Thanks in advance.

You have quite a lot of problems here. For starters, in your first loop, $qQty is undefined.

Hi m@tt.

You are quite correct: it is udefined in the first path (and that is OK), but it is after the “submit”.
That loop works as expected and collects the answers after a submit.

I can insert a test for $process == ‘check’ and execute the loop only if that is true (which it would be after a sumit).

That loop is never executed… $qQty will always be undefined.

Can I ask what is your goal? Why do you need to store the answers in a session?

I put this together for you to try and show you the proper way to handle radio arrays. I did modify your array slightly. I hope it helps.

[php]

<?php $questions = array( array( 'title' => "Conditions of Participation", 'questions' => array( array("Dogs do not need a tattoo or microchip to compete in French Ring Sport as long as they are registered with a breed affiliation.","1.1.2","B","false"), array("Members are only allowed to compete with 3 Blue dogs in their lifetime.","1.1.6","B","false"), array("A female dog in heat must compete after all the other dogs in the trial.","1.1.10","B","true"), array("An individual decoying a trial is authorized to compete his or her own dog, as long as the dog is presented by another handler.","1.1.11","B","false") ) ), array( 'title' => "The following is needed to hold a trial:", 'questions' => array( array("A judge and a deputy judge.","1.2.6","B","true"), array("A Ring Steward.","1.2.6","B","false"), array("A blank revolver or something that make a similar noise.","1.2.6","B","false"), array("A horn.","1.2.6.","B","true"), array("A minimum of eight cones or flags.","1.2.6","B","true"), array("A minimum of eight pieces of food for the Food Refusal exercise.","1.2.6","B","false") ) ) ); $num_correct = 0; $num_incorrect = 0; echo "\n"; echo "\n"; // loop question groups foreach($questions as $group_key => $group) { echo "\n"; // use $group_key as question number echo "\n"; // build questions array using answers[group_key][key] foreach($group['questions'] as $key => $question) { // set submitted value if exists $value = (isset($_POST['answers'][$group_key][$key]) ? $_POST['answers'][$group_key][$key] : null); // count correct/wrong answers only where an answer was provided if ($value !== null) { if ($value === $question[3]) { $num_correct++; } else { $num_incorrect++; } } // create question echo "\n"; echo "\n"; echo "\n"; echo "\n"; } } echo "
Question " . ($group_key + 1) . "
" . $group['title'] . "
\n"; echo " True"; // checked if value == true echo " False\n"; // checked if value == false echo "" . $question[0] . "
\n"; echo "\n"; echo "\n"; // output results if submitted if (isset($_POST['answers'])) { echo "Correct: " . $num_correct . ", Incorrect: " . $num_incorrect; } ?>

[/php]

m@tt, thank you so much for the help.

To answer your earlier questions:

  1. My goal is to build a reuseable template script to implement multiple quizzes. I am using the first of the quizzes to implement the template script.

  2. I thought $_session would be required since many people could be using the same quiz concurrently.

Now I have printed out the code you posted and am learning quit a bit from it. I think I have understood all of it and how it works but have a question about:

[php]$value = (isset($_POST[‘answers’][$group_key][$key]) ? $_POST[‘answers’][$group_key][$key] : null);[/php]

From what I assume it should be doing, the “?” prefixes what is executed if the first part of the isset is true, and the “:” prefixes what should be executed if it does not. I have looked trough my PHP for Dummies book and php.net/.../manual etc., and cannot find any explanation about the uses of “?” and “:” that you have done. Please let me know if I assumed correctly and where else these special characters may be used with the same meaning (or point me to where I can find that answer).

In just a few weeks I have learnt a lot about PHP and I have to thank you for some of that.

Thanks again.

You are correct. (condition ? true : false)

This is a common practice in many languages and a very useful one :slight_smile:

[php]$value = (isset($_GET[‘value’]) ? $_GET[‘value’] : null);[/php]

Is equivalent to doing:

[php]
$value = null;
if (isset($_GET[‘value’])) {
$value = $_GET[‘value’];
}
[/php]

Here is a reference on PHP.net

http://php.net/manual/en/language.operators.comparison.php

“Ternary Operator”

Sponsor our Newsletter | Privacy Policy | Terms of Service