Page 1 of 1

first time using arrays

Posted: Mon Dec 05, 2005 3:26 am
by php3ch0
Hi everyone

This is my first time using arrays. I am creating a quiz and putting the answers into a $_SESSION['answers_array'];

I am having problems with the following code. It is setting values to:

Code: Select all

$answers_array['quiz_id']
and

Code: Select all

$answers_array['quiz_id']['question_number']
but not to:

Code: Select all

$answers_array['quiz_id']['question_number']['optionid']
or

Code: Select all

$answers_array['quiz_id']['question_number']['optionid']['answer']
I have posted the full code below please can you help!

(Please ignore the echo ""; as these are part of the debug check)

Code: Select all

require_once('../../php/page_functions.php'); 
require_once('../../Connections/db_connect.php');

if(empty($_POST['quiz_id']) or empty($_SESSION['question_number'])) { header("Location:index.php"); }

$quiz_id = $_POST['quiz_id'];
$question_number = $_SESSION['question_number'];

// seting vars to 0
	$total_sent_answers = '0';

// database queries

mysql_select_db($database_db_connect, $db_connect);
$query_quiz_top = "SELECT * FROM quizzes_top WHERE id = '$quiz_id' ORDER BY id DESC";
$quiz_top = mysql_query($query_quiz_top, $db_connect) or die(mysql_error());
$row_quiz_top = mysql_fetch_assoc($quiz_top);
$totalRows_quiz_top = mysql_num_rows($quiz_top);

mysql_select_db($database_db_connect, $db_connect);
$query_question = "SELECT * FROM quizzes WHERE question_number = '$question_number' AND quiz_id = '$quiz_id' ORDER BY id ASC";
$question = mysql_query($query_question, $db_connect) or die(mysql_error());
$row_question = mysql_fetch_assoc($question);
$totalRows_question = mysql_num_rows($question);


mysql_select_db($database_db_connect, $db_connect);
$query_options = "SELECT * FROM quiz_options WHERE question_id = '$question_number' AND quiz_id = '$quiz_id' ORDER BY id ASC";
$options = mysql_query($query_options, $db_connect) or die(mysql_error());
$row_options = mysql_fetch_assoc($options);
$totalRows_options = mysql_num_rows($options);

mysql_select_db($database_db_connect, $db_connect);
$query_options_correct = "SELECT * FROM quiz_options WHERE question_id = '$question_number' AND quiz_id = '$quiz_id' AND correct = 'Y' ORDER BY id ASC";
$options_correct = mysql_query($query_options_correct, $db_connect) or die(mysql_error());
$row_options_correct = mysql_fetch_assoc($options_correct);
$totalRows_options_correct = mysql_num_rows($options_correct);


// setting array
if(!isset($answers_array)){ $answers_array = array(); }
	
//setting array vars (3d array)
		$answers_array[$quiz_id] = $quiz_id;
		echo "quiz_id :".$answers_array[$quiz_id]."<br>";
 		$answers_array[$quiz_id][$question_number] = $question_number;	
 		echo "question number: ".$answers_array[$quiz_id][$question_number]."<br>";
//checking vars and putting into array		
 		do{
 			$optionid = $row_options['id'];
 			echo $optionid;
 			$answers_array[$quiz_id][$question_number][$optionid] = $optionid;
 			echo "option id: ".$answers_array[$quiz_id][$question_number][$optionid]."<br>";
 			$answervar = "option".$optionid;
 			$answer = $_POST[$answervar];
 				// set answer to no if not Yes
 				if ($answer <> 'Y') { $answer = 'N'; 
 					} else {
 				$total_sent_answers++; 
 					}

 			
 			$answers_array[$quiz_id][$question_number][$optionid][$answer] = $answer;
 		session_register($answers_array);
 		} while ($row_options = mysql_fetch_assoc($options));
 		 		// counting correct answers and redirecting if no correct amount
 				if($total_sent_answers <> $totalRows_options_correct) { 
 					//echo "<br>sent answers: $total_sent_answers";
 					//echo "<br>total correct answers: $totalRows_options_correct";
 					//echo "<br>question number: $question_number";
 					header("Location:take_quiz.php?quiz_id=".$quiz_id."&error=options"); 
 				}
 				
 				if($total_sent_answers == $totalRows_options_correct) {
 						//echo "<br>sent answers: $total_sent_answers";
 						//echo "<br>total correct answers: $totalRows_options_correct";
 						//echo "<br>question number: $question_number";
 						
					 	$question_number++;
					 	session_register($question_number);
						 	if($question_number > $row_quiz_top['no_of_questions']) { 
								// collecting information
								$username = $_SESSION['MM_Username'];
								$score = base64_encode(serialize($answers_array));
								$date = date('d/m/Y');
								//inserting data ito database
								mysql_select_db($database_db_connect, $db_connect);
								$insert_sql = "INSERT INTO quiz_scores(username,score,date,quiz_id) 
															VALUES('$username','$score','$date','$quiz_id')";
								mysql_query($insert_sql, $db_connect) or die(mysql_error());
								
									

								
						 		header("Location:results.php?quiz_id=$quiz_id");
						 	} else {
						 		header("Location:take_quiz.php?quiz_id=$quiz_id");
						 	}
 	
 				}

Posted: Mon Dec 05, 2005 3:48 am
by Chris Corbyn
You need to restructure your array something like:

Code: Select all

Array (
    [$quiz_id] => Array (
        'question_number' => 23,
        'option_id' => 12,
        'answer' => 7
    )
)
At the moment you're trying to add elements on top of each other.... whereas what you should is delare the first element (quiz_id) as an array itself:

Code: Select all

$questions = array();
$questions[$quiz_id] = array(); //Now we have an array inside an array
$questions[$quiz_id]['question_no'] = $qu;
$questions[$quiz_id]['option'] = $opt;
$questions[$quiz_id]['answer'] = $ans;
Get your code to follow that kind of a pattern ;)

Posted: Mon Dec 05, 2005 3:49 am
by onion2k
You can't put any complex data type like an array directly into a user's session. You need to convert it into something that can be stored instead. Handily PHP has a function specifically for doing this..

Code: Select all

$_SESSION['session_array'] = serialize($array);
On your next page when you need to get the array back again..

Code: Select all

if (isset($_SESSION['session_array'])) {
  $array = unserialize($_SESSION['session_array']);
} else {
  $array = array();
}
Of course, this stops you relying on register_globals variables .. but you shouldn't be doing that anyway.

Posted: Mon Dec 05, 2005 4:51 am
by php3ch0
Thanks people I'll give that a try.

It definately makes more sense to do it that way.

Dan

Posted: Mon Dec 05, 2005 5:10 am
by m3mn0n
Hope it works out.

Just another note: using print_r ($array_name) helps a lot with debugging. It's good to format the output of that with <pre> & </pre> too. :)

Posted: Mon Dec 05, 2005 5:25 am
by Skittlewidth
onion2k wrote:You can't put any complex data type like an array directly into a user's session.
Just out of interest, is that you can't or you shouldn't?

I've been putting arrays, and even objects into Sessions without serializing them without problems, but does that mean I'm creating unnecesary overheads? 8O

Posted: Mon Dec 05, 2005 5:26 am
by shiznatix
a very helpful function when dealing with arrays is dump()

Code: Select all

function dump($arr)
{
  echo '<pre>';
  print_r($arr);
  echo '</pre>';
}

//then when you want to see a array in full just
dump($array);
very very helpful

Posted: Mon Dec 05, 2005 5:32 am
by onion2k
Skittlewidth wrote:I've been putting arrays, and even objects into Sessions without serializing them without problems, but does that mean I'm creating unnecesary overheads? 8O
Oh. I thought you had to serialize things to store them. Maybe PHP automagically serializes things now. It didn't a long time ago.

Posted: Mon Dec 05, 2005 5:34 am
by foobar
shiznatix wrote:a very helpful function when dealing with arrays is dump()
[...]
very very helpful
I second that! Absolutely invaluable! I use it for debugging _all_ the time. print_r() is truly a gift of God. Working with multi-dimensional arrays (even 2-d arrays as a matter of fact) can get very confusing pretty quickly. Do a check of what your array looks like after transforming it in some way.

Posted: Mon Dec 05, 2005 5:47 am
by Chris Corbyn
onion2k wrote:
Skittlewidth wrote:I've been putting arrays, and even objects into Sessions without serializing them without problems, but does that mean I'm creating unnecesary overheads? 8O
Oh. I thought you had to serialize things to store them. Maybe PHP automagically serializes things now. It didn't a long time ago.
You can store anything you like in sessions. I even store database connections in there ;) I don't think there's any hidden serialization going on... it's just references to things in memory.

Posted: Wed Dec 14, 2005 5:58 am
by php3ch0
Thanks everyone it is working fine !