Jump to content

Recommended Posts

http://www.elanman.co.uk/2009/03/make-your-own-php-quiz-part-1/

 

This was the tutorial I was using, with all the code. Even his example that is pretty much identical to mine just works.

 

I think I actually see where the problem is that you are running into. In step 4 of the tutorial it shows code for if they are registered or not and then starts the session:

if (isset($_POST['register'])) { // they want to register
    $username = trim(strip_tags(stripslashes($_POST['username'])));
    if (ini_get('magic_quotes_gpc')) {
        $username = stripslashes($username);
    }
} else { //they don't want to register
    $random = rand(1,1000);
    $username = 'Anon'. $random;
} //end of if/else conditional</strong>
$num = 0;

If you notice, there is a $num = 0; just after that section. Check to see if that is in your code. That makes a big difference.

	
	$_SESSION['user'] = $username;
	$_SESSION['score'] = 0;
	$_SESSION['correct'] = array(); 
	$_SESSION['wrong'] = array();
	$_SESSION['finished'] = 'no';
	if (isset($_SESSION['error']))
	unset($_SESSION['error']); 
	$num = 0;
} else {
	$random = rand(1,1000);
	$_SESSION['user'] = 'Anon'. $random;
	$_SESSION['score'] = 0;
	$_SESSION['correct'] = array(); 
	$_SESSION['wrong'] = array(); 
	$_SESSION['finished'] = 'no';
	$num = 0;
}

 

There is my code. I have the num 0 in there and it still doesnt work!

First off, according to the tutorial, your $num=0; is in the wrong place. If you look at the code it looks like this:

if (isset($_POST['register'])) {
    $username = trim(strip_tags(stripslashes($_POST['username'])));
} else {
    $random = rand(1,1000);
    $username = 'Anon'. $random;
} //end of if/else conditional</strong>
$num = 0;
$_SESSION['user'] = $username; // username
$_SESSION['score'] = 0; // score set to 0
$_SESSION['correct'] = array(); // to hold the user's correct answers
$_SESSION['wrong'] = array(); // to hold the user's incorrect answers
$_SESSION['finished'] = 'no'; // they haven't finished the quiz yet

 

Without knowing your full if-else statement, no one can tell what is going on in that code. It could be that it isn't even calling that if-else statement at all. Plus the includes and placement of your code is important. The tutorial uses 3 pages. it is hard to tell from the snippets of code that you provide whether you have them in the right pages to begin with.

I moved the two $nums = 0 's and it did nothing. Answer one is still the right one with no change. I didnt even have to copy the code. He gives all the source files for download. All I had to do was take them and modify the questions. But it still doesnt work. I have looked through the entire tutorial like twice and went over the code and there is no difference I really have no idea why it isnt working for me.

Ok I will put ever single bit of code I am using down. I really appreciate the help guys.

 

Index.php

<?php //index.php
session_name("Acronym_Test");
session_start();
$_SESSION['score'] = 0;
$_SESSION['correct'] = array(); 
$_SESSION['wrong'] = array();
$_SESSION['finished'] = 'no'; 
$_SESSION['num'] = 0;
require_once ('functions.php');
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<link rel="stylesheet" href="style.css" type="text/css" />
<title>The Web Acronym Test</title>
<script type="text/javascript" src="start.js"></script>
</head>
<body id="splash">
<div id="wrapper">
<div id="intro">
<h1>Take the test and see how well you know your web acronyms</h1>
<p>Each acronym has 4 possible answers. Choose the answer you think is correct and click <strong>'Submit Answer'</strong>. You'll then be given the next acronym.</p>
<p>There are 20 acronyms, so let's get cracking! You'll get your score at the end of the test. It's just like facebook (honest!).</p>
<div id="leaderboard">
<h2>Top 10 Scorers</h2>
<?php 
showLeaders('leaders.xml',10,5);
?>
</div><!-- leaderboard-->
</div><!--intro-->
<div id="quiz">
<h2>Start The Test</h2>
<p>If featuring on the Score Board is of absolutely no interest to you,</p>
<form id="jttt" method="post" action="test.php">
<p><input type="submit" value="Just Take The Test" /></p>
</form>
<form id="questionBox" method="post" action="test.php">
<p>If you want to be placed on the 'Top Scorers' list, please enter a username below.</p> 
<ul>
<li><label for="username">Create A Username:</label><br />
<input type="text" id="username" name="username" value="Username" />
<p id="exp">Username must be between 3 and 10 characters in length</p></li>
</ul>
<p><input type="hidden" name="register" value="TRUE" />
<input type="submit" id="submit" value="Register And Take The Test" /></p>
</form> 
<p id="helper"><?php if(isset($_SESSION['error'])) echo $_SESSION['error']; ?></p>
</div><!--quiz-->
</div><!--wrapper-->
</body>
</html>

 

test.php

<?php //test.php

session_name("Acronym_Test");
session_start();
require_once('questionsandanswers.php');
require_once('functions.php');
if (!isset($_POST['submitter'])) {

    if(isset($_POST['register'])) {
	$username = trim(strip_tags(stripslashes($_POST['username'])));
	$file = "leaders.xml";
		$xml = simplexml_load_file($file);
	foreach($xml->user as $user) {
		if ($user->name == $username) {
			$_SESSION['error'] = 'That name is already registered, please choose another.';
			header('Location: index.php');
			exit();
			}
		}

	$_SESSION['user'] = $username;
	$_SESSION['score'] = 0;
	$_SESSION['correct'] = array(); 
	$_SESSION['wrong'] = array();
	$_SESSION['finished'] = 'no';
	if (isset($_SESSION['error']))
	unset($_SESSION['error']); 
	$num = 0;
} else {
	$random = rand(1,1000);
	$_SESSION['user'] = 'Anon'. $random;
	$_SESSION['score'] = 0;
	$_SESSION['correct'] = array(); 
	$_SESSION['wrong'] = array(); 
	$_SESSION['finished'] = 'no';
	$num = 0;
}
} else {
$num = (int) $_POST['num'];
$postedanswers = str_replace("_"," ",$_POST['answers']);
if ($postedanswers == $answers[$num]['0']) {
	$_SESSION['score']++;
	$_SESSION['correct'][] = $postedanswers; 
} else {
	$_SESSION['wrong'][] = $postedanswers;
} 
if ($num < count($questions)-1) {
	$num++;
} else {
	$last = true;
	$_SESSION['finished'] = 'yes';
}
} 
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<link rel="stylesheet" href="style.css" type="text/css" />
<title>The Web Acronym Test</title>
<?php 
if (!isset($last)) {
echo "<script type=\"text/javascript\" src=\"form.js\"></script>";
}
?>
</head>
<body>
<div id="wrapper">
<div id="intro">
<h1>Take the test and see how well you know your web acronyms</h1>
<p>Each acronym has 4 possible answers. Choose the answer you think is correct and click <strong>'Submit Answer'</strong>. You'll then be given the next acronym.</p>
<p>There are 20 acronyms, so let's get cracking! You'll get your score at the end of the test. It's just like facebook (honest!).</p>
<?php if(isset($_SESSION['user'])) echo "<h4>Current tester: {$_SESSION['user']}</h4>"; ?>
</div><!--intro-->
<div id="quiz">
<?php 
if (!isset($last)) {  ?>
<h2>Acronym <?php echo $num+1; ?>:</h2>
<p>What does <strong><?php echo $questions[$num]; ?></strong> stand for?</p>
<form id="questionBox" method="post" action="test.php">
<ul>
<?php 
$pattern = ' ';
$replace = '_';
shuffle_assoc($answers[$num]);
foreach ($answers[$num] as $answer) {
$answer2 = str_replace($pattern,$replace,$answer);
echo "<li><input type=\"radio\" id=\"$answer2\" value=\"$answer2\" name=\"answers\" />\n";
echo "<label for=\"$answer2\">$answer</label></li>\n";
}
?>
</ul>
<p><input type="hidden" name="num" value="<?php echo $num; ?>" />
<input type="hidden" name="submitter" value="TRUE" />
<input type="submit" id="submit" name="submit" value="Submit Answer" /></p>
</form>
<?php } else { 
$file = "leaders.xml";
$xml = simplexml_load_file($file);
$user = $xml->addChild('user');
$uname = $user->addChild('name',$_SESSION['user']);
$uscore = $user->addChild('score',$_SESSION['score']);
$xml->asXML("leaders.xml");

echo "<h2 id=\"score\">{$_SESSION['user']}, your final score is:</h2>\n
<h3>{$_SESSION['score']}/20</h3><h4>Verdict:</h4>";
if($_SESSION['score'] <= 5) echo "<p id=\"verdict\"><span>S</span>everely <span>H</span>indered <span>I</span>n the <span>T</span>est!</p>\n";
if(($_SESSION['score'] > 5) && ($_SESSION['score'] <= 10)) echo "<p id=\"verdict\"><span>C</span>ould <span>R</span>ead <span>A</span>nd <span>P</span>ractice more.</p>\n";
if(($_SESSION['score'] > 10) && ($_SESSION['score'] <= 15)) echo "<p id=\"verdict\"><span>A</span>cronyms a<span>R</span>e <span>S</span>o <span>E</span>asy!</p>\n";
if($_SESSION['score'] > 15) echo "<p id=\"verdict\"><span>S</span>uper <span>A</span>cronym <span>S</span>pecialist</p>";
echo "<p id=\"compare\"><a href=\"results.php\">See how you compare! <img src=\"images/arrow.png\" /></a></p>";
}
?>
</div><!--quiz-->
</div><!--wrapper-->
</body>
</html>

 

functions.php

<?php //functions.php

function shuffle_assoc(&$array) {
$keys = array_rand($array, count($array));
foreach($keys as $key)
    	$new[$key] = $array[$key];
    $array = $new;
        return true;
}
  
function showLeaders($file,$limit,$group = null) { 
$leaders = array();

// Load the xml file and place all users and associated 
	// scores into the 'leaders' array.
	$xml = simplexml_load_file($file);
	foreach($xml->user as $user) {
		$name = (string)$user->name;
		$score = (string)$user->score;
		$leaders[$name] = $score;
	}

	// Sort the leaders array numerically, highest scorers first.	
	arsort($leaders,SORT_NUMERIC);

	// Initialise our $counter variable to '1'.
	$counter = 1;

	// Start a html ordered list to hold the leaders.
	$output = "<ul class=\"leaders\">\n";

	// Loop through the 'leaders' array and wrap each username and score
	// in <li> tags. If the user is the current $_SESSION['user'], wrap
	// the name/score in <strong> tags too.
	foreach ($leaders as $key => $value) {
		// Check that $counter is less than $limit.
		if ($counter <= $limit) {
			if ($key == $_SESSION['user']) {
				$output .= "<li><strong>$key:</strong> $value/20</li>\n";
			} else {
				$output .= "<li>$key: $value/20</li>\n";
			}
			// Check to see if $group parameter has been passed.
			// If it has, create separate lists according to the $group variable.
			if ($group) {
				// Use the modulus operator(%) to create new sub-list.
				if($counter % $group == 0) {
					$output .= "</ul>\n<ul class=\"leaders\">\n";
				}
			}
		}
	// Increment the $counter.	
	$counter++;
	}
	// End the ordered list.
	$output .= "</ul>\n";

	// Print out the ordered list.
echo $output;
}

function showAnswers($answers,$questions) { 
for($x = 0; $x< count($answers); $x++) {
	if ($x % 2 == 0) { 
	 	$output = "<div class=\"qanda clear\">\n";
	} else { 
		$output = "<div class=\"qanda\">";
  		}
	$output .= '<h4>Anacronym' . ($x+1) . ': ' . $questions[$x] . '</h4>'; 
$output .= "<ol>\n";
	for ($y = 0;$y< count($answers[$x]); $y++) {
		if (($answers[$x][$y] === $answers[$x][0]) && (in_array($answers[$x][$y],$_SESSION['correct']))) {
			$output .= "<li class=\"correctuser\">{$answers[$x][$y]} (Correct!)</li>\n";
		} else if ($answers[$x][$y] === $answers[$x][0]) {
			$output .= "<li class=\"correct\">{$answers[$x][$y]}</li>\n";
		} else if (in_array($answers[$x][$y],$_SESSION['wrong'])) {
			$output .= "<li class=\"wrong\">{$answers[$x][$y]} (Woops!)</li>\n";
		} else { 
			$output .= "<li>{$answers[$x][$y]}</li>\n";
	}
}
$output .= "</ol></div>\n";
echo $output;
}
}
?>	

 

questionsandanswers.php

<?php
$questions = array('FTP','AJAX','RSS','XSS','PHP','W3C','XML','YUI','HTML','CGI','SSL','SQL','HTTP','CSS','SOAP','WAI','SSI','JSON','XSLT','WCAG');
$answers = array(
array(0 =>'File Transfer Protocol','Force Through Privately','File Through Protocol','File Test Protocol'),
array(0 => 'Asynchronous JavaScript and XML','All JavaScript and XML','Alternative Java and XML','Actual JavaScript and XML'),
array(0 => 'Really Simple Syndication','Really Simple Scripting','Ready-Styled Scripting','Really Stupid Syndication'),
array(0 => 'Cross-site Scripting','Cross-site Security','Cleverly Structured Scripting','eXtremely Safe and Secure'),
array(0 => 'PHP: Hypertext Preprocessor','Post Hypertext Processor','Practical HTML Processing','Process HTML Prettily'),
array(0 => 'World Wide Web Consortium','World Wide Web Committee','World Wide Web Creatives','Wakefield Willy Wavers Club'),
array(0 => 'eXtensible Markup Language','eXtendable Markup Language','Crossover Markup Language','eXtreme Markup Language'),
array(0 => 'Yahoo User Interface','Yahoo\'s Useful Idea','Yahoo Utility Interface','Yahoo User Interaction'),
array(0 => 'Hypertext Markup Language','Human Markup Language','Helpful Markup Language','Hypertext Memory Language'),
array(0 => 'Common Gateway Interface','Common or Garden Interaction','Computer\'s Graphical Intelligence','Common Graphical Interface'),
array(0 => 'Secure Sockets Layer','Server Security Layer','Server Security Level','Secret Socket Layer'),
array(0 => 'Structured Query Language','Stupid Query Language','Secure Query Language','Strict Query Language'),
array(0 => 'Hypertext Transfer Protocol','Hypertext Traffic Protocol','HTML Traffic Transfer Protocol','HTML Through Traffic Protocol'),
array(0 => 'Cascading Style Sheets','Custom Style Sheets','Clientside Style Sheets','Calculated Style Sheets'),
array(0 => 'Simple Object Access Protocol','Structured Object Access Protocol','Simple, Objective And Private','Simply Obvious Access Principle'),
array(0 => 'Web Accessibility Initiative','World Wide Accessibility Intiative','World Wide Accessibility Incorporation','Web Accessibility and Inclusion'),
array(0 => 'Server-Side Include','Server-Side Intelligence','Scripted Server Include','Secure Server Include'),
array(0 => 'JavaScript Object Notation','JQuery-Scripting Object Notation','Just Simple Object Notation','JavaScript Over the Net'),
array(0 => 'eXtensible Stylesheet Language Transformation','eXpandable Stylesheet Language Transfer','eXtensible Stylesheet Language Transfer','eXtendable Stylesheet Language Transformation'),
array(0 => 'Web Content Accessibility Guidelines','Wakefield Community Action Group','Web Criteria And Guidelines','World-wide Common Access Group')
); 
?>

 

results.php

<?php //results.php
session_name("Acronym_Test");
session_start();
if($_SESSION['finished'] != 'yes') {
header('Location: index.php');
}
include_once('questionsandanswers.php');
include_once('functions.php');
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<link rel="stylesheet" href="style.css" type="text/css" />
<title>The Web Acronym Test Results</title>
</head>
<body id="resultpage">
<div id="wrapresult">
<h1>The Results Page For <span><?php echo $_SESSION['user']; ?></span></h1>
<div id="intro">
<h2>Top 20 Scorers</h2>
<?php showLeaders('leaders.xml',20); ?>
</div><!--intro-->
<div id="quiz">
<?php showAnswers($answers,$questions); ?>	
</div><!--quiz-->
<ul id="footer" class="clear">
<li><a href="index.php" title="Start The Quiz Again">Start Again</a></li>
<li><a href="http://www.elanman.co.uk/2009/03/make-your-own-php-quiz-part-1/" title="Return To ElanMan's Drawers">Return To The Blog</a></li>
</ul>
</div><!--wrapper-->
</body>
</html>

 

leaders.xml

<?xml version="1.0" encoding="UTF-8"?>
<users>
  <user>
  	<name>Bobby</name>
    <score>10</score>
  </user>
  <user>
  	<name>Billy</name>
    <score>1</score>
  </user>
</users>

 

start.js

window.onload = function () {
document.getElementById('username').onfocus = function(evt) {
	if(this.value == 'Username') this.value = '';
	document.getElementById('helper').innerHTML = '';
	}
document.getElementById('username').onblur = function(evt) {
	if(this.value == '') this.value = 'Username';
	}
document.getElementById('questionBox').onsubmit = function() {return checkForm();};
}

function checkForm() {
if ((document.getElementById('username').value == '') || (document.getElementById('username').value == 'Username') || (document.getElementById('username').value.length < 3) || (document.getElementById('username').value.length > 10)) {
document.getElementById('helper').innerHTML = 'To register, please enter your own username between 3 and 10 characters in length';
	return false;
}
}

 

form.js

window.onload = function () {
document.getElementById('submit').disabled = true;
var qform = document.getElementById('questionBox');
var inputs = qform.getElementsByTagName('input');
for(var i = 0; i < inputs.length;i++) {
	inputs[i].onclick = function(evt) { checkForm();};
}
}

function checkForm() {
document.getElementById('submit').disabled = false;
}

 

Thats EVERYTHING every single bit of code involved in this. Thanks for the help. Any help you can give would be amazing!

I just noticed you can attach files. Here is all the source files downloaded all ready to go. I havn't touched them at all. They just dont shuffle for me.

Sorry I didn't post this before. I just noticed now that you can include files.

 

[attachment deleted by admin]

Yes, I DID see that. I was responding to your statements "I just noticed you can attach files ... I just noticed now that you can include files." Funny how you just noticed that today when I mentioned it yesterday.

 

I already copied the code from your post yesterday. I just haven't had the time to sift through it.

Have you had any luck mjdamato? or had a chance to look over the code at all yet?

 

Upon initial inspection it did seem to present the same problem, but then after playing around with it for a while it seemed to work correctly. I have to assume that it has something to do with the SESSION variables. I haven't had time to dive into it more. Personally, it wouldn't be worth my time. I could probably rewrite a better solution in less time than it would take to fix that code. But, I just don't have the time right now.

You cant post the code you messed about with to get it working or anything? or what you changed to get it working correctly?

?

 

Well, I was only modifying the code to output data to the screen so I could see some of the internal variables to see what was going on. When it started to work I undid my changes, and it continued to work. So, the problem was not "fixed" by anything I did. That is why I assume it has something to do with the session variables.

  • 1 month later...

Hey guys,

 

I dont know what the big deal is.

The answer is really simple and you guys just missed out a line.

Just copy and paste this code and it would work fine.

 

I have highlighted in bold the missing line which should of been included.

 

function shuffle_assoc(&$array) {

$keys = array_rand($array, count($array));

shuffle($keys);

foreach($keys as $key)

    $new[$key] = $array[$key];

    $array = $new;

        return true;

}

 

I found the answer by looking up some coding on the php.net

 

Hope this solved your problems :)

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.