first time using arrays

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
php3ch0
Forum Contributor
Posts: 212
Joined: Sun Nov 13, 2005 7:35 am
Location: Folkestone, Kent, UK

first time using arrays

Post 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");
						 	}
 	
 				}
User avatar
Chris Corbyn
Breakbeat Nuttzer
Posts: 13098
Joined: Wed Mar 24, 2004 7:57 am
Location: Melbourne, Australia

Post 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 ;)
User avatar
onion2k
Jedi Mod
Posts: 5263
Joined: Tue Dec 21, 2004 5:03 pm
Location: usrlab.com

Post 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.
User avatar
php3ch0
Forum Contributor
Posts: 212
Joined: Sun Nov 13, 2005 7:35 am
Location: Folkestone, Kent, UK

Post by php3ch0 »

Thanks people I'll give that a try.

It definately makes more sense to do it that way.

Dan
User avatar
m3mn0n
PHP Evangelist
Posts: 3548
Joined: Tue Aug 13, 2002 3:35 pm
Location: Calgary, Canada

Post 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. :)
User avatar
Skittlewidth
Forum Contributor
Posts: 389
Joined: Wed Nov 06, 2002 9:18 am
Location: Kent, UK

Post 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
User avatar
shiznatix
DevNet Master
Posts: 2745
Joined: Tue Dec 28, 2004 5:57 pm
Location: Tallinn, Estonia
Contact:

Post 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
User avatar
onion2k
Jedi Mod
Posts: 5263
Joined: Tue Dec 21, 2004 5:03 pm
Location: usrlab.com

Post 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.
foobar
Forum Regular
Posts: 613
Joined: Wed Sep 28, 2005 10:08 am

Post 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.
User avatar
Chris Corbyn
Breakbeat Nuttzer
Posts: 13098
Joined: Wed Mar 24, 2004 7:57 am
Location: Melbourne, Australia

Post 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.
User avatar
php3ch0
Forum Contributor
Posts: 212
Joined: Sun Nov 13, 2005 7:35 am
Location: Folkestone, Kent, UK

Post by php3ch0 »

Thanks everyone it is working fine !
Post Reply