Page 1 of 1

I am looking to make a test show percentages

Posted: Wed Mar 10, 2010 12:52 pm
by Doctor-Eggman
Hi all I am looking to make a PHP based test and found some really handy code online. I am a pretty big PHP newbie so get stuck easily. At the present time the answers to the test show the results in a format like 14/20 "you got 14 out of 20 correct" sort of thing. Instead of that /20 I am looking to get the answers to display in a percentage of what they got correct. Here presently is the code for it. At least I think this is the answer script code. As I say I am pretty new to this.

} 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';
}


Any help at all would be greatly appreciated. Thank you

Re: I am looking to make a test show percentages

Posted: Wed Mar 10, 2010 1:11 pm
by AbraCadaver
This isn't the code that does that.

Re: I am looking to make a test show percentages

Posted: Thu Mar 11, 2010 7:19 am
by Doctor-Eggman
Awww I looked through all the code and even the tutorial I used and it said that was the code for where the correct answers went. I couldnt find anything else that looked like it could be where the answers are being counted up. I am so confused.

Re: I am looking to make a test show percentages

Posted: Thu Mar 11, 2010 3:55 pm
by Doctor-Eggman

Code: Select all

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>
That is ALL the code from the test page. Does anyone have ANY idea how I could make it display a percentage?

Re: I am looking to make a test show percentages

Posted: Thu Mar 11, 2010 4:18 pm
by Doctor-Eggman
I mean what I am really looking for is so that when an answer is pressed it goes up by say 0.25 percent or something. rather than going up by one does anyone know a way to do this?

Re: I am looking to make a test show percentages

Posted: Thu Mar 11, 2010 4:53 pm
by lshaw

Code: Select all

 
echo "<h2 id=\"score\">{$_SESSION['user']}, your final score is:</h2>\n
 <h3>{$_SESSION['score']}/20</h3><h4>Verdict:</h4>";
 
//changed code
$percent=$_SESSION['score']/20*100; //work out a percentage, divide the score by total an *100
echo "<p>Your Percentage: ".$percent."</p>";
 
 
 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>";
}
 

Re: I am looking to make a test show percentages

Posted: Fri Mar 12, 2010 4:53 am
by Doctor-Eggman
You are a genius Ishaw A complete genius.

I am moving in the right direction now. The only thing I really need help with now is...is there anyway to get that the percentage is the only one shown and the score out of 20 isnt shown at all. Also the score out of 20 goes to a leaderboard what I want is the percentage to go to the leaderboard instead.
Any help and I would be exstatic.

Code: Select all

<?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>";
 
//changed code
$percent=$_SESSION['score']/20*100; //work out a percentage, divide the score by total an *100
echo "<p>Your Percentage: ".$percent."</p>";
 
 
 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>";
}
 ?>
Thats the code in the test part that I belive will send it to the leaderboard.

This is the code in the XML file that is storing the the leader information

Code: Select all

<?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>
 
and this is the show leaders code from the functions.

Code: Select all

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;
 }
I know I am a pain in the ass but if anyone can help me that will be all I need and I will be insanely grateful you have been so helpful so far and I really appreciate it. Many thanks!

Re: I am looking to make a test show percentages

Posted: Fri Mar 12, 2010 2:02 pm
by Doctor-Eggman
I have been looking at the code all night and cant quite figure it out. I think I am supposed to do something here

Code: Select all

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;
}
To get it to show the percentage in the leaderboard but I am not sure...or am i supposed to be getting the percentage score into the xml file? I am stuck on this one. ishaw you were insanely helpful before do you have any idea on this?

Re: I am looking to make a test show percentages

Posted: Fri Mar 12, 2010 3:34 pm
by lshaw
You need to insert the percentages into the XML file. If you post the code that you think inserts the scores, i may be able to help


To just show the percentage,

Code: Select all

 
//delete this line echo "<h2 id=\"score\">{$_SESSION['user']}, your final score is:</h2>\n
//delete this line <h3>{$_SESSION['score']}/20</h3><h4>Verdict:</h4>;
 
//changed code
$percent=$_SESSION['score']/20*100; //work out a percentage, divide the score by total an *100
echo "<p>Your Percentage: ".$percent."</p>";
echo "</h3><h4>Verdict:</h4>"; //show the verdict title after the score/percentage
 

Re: I am looking to make a test show percentages

Posted: Fri Mar 12, 2010 4:50 pm
by Doctor-Eggman
Ishaw you are my hero. Thats great for just showing the percentage.

Code: Select all

<?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");
 
I think that is the code that is sending it to the XML file.
Is that any help? If you can help me in any way it would be great. Any other code you would need I will track it down, that looked like the one that was sending it where it needed to go.

Re: I am looking to make a test show percentages

Posted: Fri Mar 12, 2010 5:38 pm
by lshaw

Code: Select all

 
//I changed this to a session variable
$_SESSION['percent']=$_SESSION['score']/20*100; //work out a percentage, divide the score by total an *100
echo "<p>Your Percentage: ".$_SESSION['percent']."</p>";
echo "</h3><h4>Verdict:</h4>"; //show the verdict title after the score/percentage
 

Code: Select all

 
<?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['percent']);//change this to percent
 $xml->asXML("leaders.xml");
 
This seems quite basic stuff so why dont you check out a tutorial?
http://www.tizag.com/phpT/

Re: I am looking to make a test show percentages

Posted: Sat Mar 13, 2010 6:01 am
by Doctor-Eggman
I was using a tutorial to do all this in the first place it really confuses me. I just have no head for code. Thank you for all your help Ishaw I really apprectiate it.
I tried the code there as you put. Right now though it just shows in the leadboard as nothing.
Is there something I am meant to append on the show answers function?

Code: Select all

function showLeaders($file,$limit,$group = null) { 
    $leaders = array();
    
    
    $xml = simplexml_load_file($file);
    foreach($xml->user as $user) {
        $name = (string)$user->name;
        $score = (string)$user->score;
        $leaders[$name] = $score;
    }
        
 
    arsort($leaders,SORT_NUMERIC);
    
 '.
    $counter = 1;
    
    $output = "<ul class=\"leaders\">\n";
    
 
    foreach ($leaders as $key => $value) {
        
        if ($counter <= $limit) {
            if ($key == $_SESSION['user']) {
                $output .= "<li><strong>$key:</strong> $value/20</li>\n";
            } else {
                $output .= "<li>$key: $value/20</li>\n";
            }
    
            if ($group) {
 
                if($counter % $group == 0) {
                    $output .= "</ul>\n<ul class=\"leaders\">\n";
                }
            }
        }
    
    $counter++;
    }
    $output .= "</ul>\n";
    
    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;
    }
}
Thanks again for the help

Re: I am looking to make a test show percentages

Posted: Mon Mar 15, 2010 10:28 am
by Doctor-Eggman
I was messing about in the functions and changed a few parts that said score to "percent" This did actually start showing a percent...Just not the right one. Oddly when I do the test and say get 95% the score I got then changes in the leaderboard to something like 40%. I got 100% in the test at one time then the leaderboard said I got 60% It is really odd. Any idea what could be doing it. Here is the code I changed.

Code: Select all

function showLeaders($file,$limit,$group = null) { 
    $leaders = array();
    
 
    $xml = simplexml_load_file($file);
    foreach($xml->user as $user) {
        $name = (string)$user->name;
        $score = (string)$user->score;
        $leaders[$name] = $score;
    }
        
 
    arsort($leaders,SORT_NUMERIC);
    
    
    $counter = 1;
    
    
    $output = "<ul class=\"leaders\">\n";
    
 
    foreach ($leaders as $key => $value) {
        
        if ($counter <= $limit) {
            if ($key == $_SESSION['user']) {
                $output .= "<li><strong>$key:</strong> $value/20</li>\n";
            } else {
                $output .= "<li>$key: $value/20</li>\n";
            }
        
            if ($group) {
                // Use the modulus operator(%) to create new sub-list.
                if($counter % $group == 0) {
                    $output .= "</ul>\n<ul class=\"leaders\">\n";
                }
            }
        }
    
    $counter++;
    }
    
    $output .= "</ul>\n";
    
    
    echo $output;
 }