Help with quiz code

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
cristcdl
Forum Newbie
Posts: 2
Joined: Sun Aug 10, 2014 6:18 pm

Help with quiz code

Post by cristcdl »

Hi I am using code from http://www.quest4.org/osquest4/index2.htm?ans=Correct. It Contains an Index.php file with the below code:

Code: Select all

<?php
require('class_quiz.inc.php');
$quiz=new quiz('xmldoc','test');
//$quiz=new quiz('xmldoc','learning');
//$quiz=new quiz('xmldoc','flash');
//xmldoc.xml is the name of the quiz file inside the XMLdocs directory, which is why the first paramter is xmldoc. this is used to
//change what test your doing etc
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title>Quiz</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<link href="spider.css" rel="stylesheet" type="text/css">
</head>
<body>
<?php
$quiz->do_quiz_here(); //pretty self explanatory
?>
</body>
</html>
Here is the included files code:

Code: Select all

<?php
class quiz
{
  var $script_url='http://www.quest4.org/osquest4'; //URL address to the base folder of this script, use a full URL and do NOT leave on the trailing /
  var $xml_url='XMLdocs';                       //location of XML quiz documents relative to this file

  // change above values to adjust preferences, DO NOT change anything below this line
  var $quizID;
  var $mode;
  var $current_question=1;
  var $error='';

  var $in_question=0;
  var $in_section='';

  var $parseXML_cache=null;
  var $parsed_XML=array();

  function quiz($quizID,$mode='test')
  {
    $this->quizID=$quizID;
    $this->mode=strtolower($mode);
    if(!($this->mode=='test' || $this->mode=='learning' || $this->mode=='flash')){
      $this->error='Error: "'.$this->mode.'" is not a valid quiz mode. valid modes are "test" "learning" and "flash"';
    }
    $this->xml_url=dirname(__FILE__).'/'.$this->xml_url;
  }
  function do_quiz_here()
  {
    if(isset($_POST['next_question'])){
      if(!isset($_POST['answers'][$_POST['next_question']-1]) && $this->mode!='flash'){
        $_POST['next_question']=$_POST['next_question']-1;
      }
      $this->print_question($_POST['next_question']);
    }else{
      unset($_POST);
      $this->print_question(1);
    }

  }
  function print_question($question_num)
  {
    $question_num=(int)$question_num;
    $data=$this->parseXML($this->quizID.'.xml');
    if($data!==false)
    {
      $a=$this->parsed_XML[$question_num];
      $count_a=count($this->parsed_XML);
      //if in learning mode print previous answer
      if($question_num<=$count_a)
      {
        if($this->mode!='flash')
        {
          if($this->mode=='learning' && $question_num>1)
          {
            $this->learning_mode_print_answer($question_num-1);
          }
          //begin printing question

          echo('
          <h4>'.$a['text'].'</h4>
          <form action="" method="post">
          <input type="hidden" name="next_question" value="'.($question_num+1).'">'."\n");
          if(isset($_POST))
          {
            foreach($_POST['answers'] as $key=>$value)
            {
              if(!is_array($value))
              {
                echo('<input type="hidden" name="answers['.$key.']" value="'.$value.'">'."\n");
              }
              else
              {
                foreach($value as $literal_key=>$valueison)
                {
                  echo('<input type="hidden" name="answers['.$key.']['.$literal_key.']" value="on">'."\n");
                }
              }
            }
          }
//                  print_r($_POST['answers']);

          if($a['type']=='radio')
          {
            foreach($a as $key=>$value)
            {
              if(strpos($key,'choice')!==false){
                echo('<input type="radio" name="answers['.$question_num.']" id="'.substr($key,6).'" value="'.substr($key,6).'"><label for="'.substr($key,6).'">'.$value.'</label><br>'."\n");
              }
            }
          }
          else if($a['type']=='blank')
          {
            echo('<input type="text" name="answers['.$question_num.']" value="" size="50"><br>'."\n");
          }
          else if($a['type']=='box')
          {

            foreach($a as $key=>$value)
            {
              if(strpos($key,'choice')!==false){
                echo('<input type="checkbox" id="answers['.$question_num.']['.substr($key,6).']" name="answers['.$question_num.']['.substr($key,6).']"><label for="answers['.$question_num.']['.substr($key,6).']">'.$value.'</label><br>'."\n");
              }
            }
          }
          echo('
          <input type="submit" value="'.($count_a==$question_num ? 'Calculate Score' : 'Next Question').'">
          </form>
          ');
        }else if($this->mode=='flash')
        {
                    //begin printing question
          $chkanswer=$this->checkanswer($question_num,1);
          echo('
          <h4>'.$a['text'].'</h4>
          <h5>Answer: '.$chkanswer['correct_answer'].'</h5>
          <h5>Explanation: '.$a['explanation'].'</h5>
          <form action="" method="post">
          <input type="hidden" name="next_question" value="'.($question_num+1).'">
          <input type="submit" value="Next Question">
          </form>
          ');
           if($question_num>1)
           {
             echo('<form action="" method="post">
                <input type="hidden" name="next_question" value="'.($question_num-1).'">
                <input type="submit" value="Previous Question">
                </form>');
           }

        }
      }
      else
      {
        if($this->mode!='flash')
        {
          if($this->mode=='learning' && $question_num>1)
          {
            $this->learning_mode_print_answer($question_num-1);
          }

          //display test results
          $total_answers=count($_POST['answers']);
          $total_correct_answers=0;
//          print_r($_POST['answers']);
//          echo('<br>');
//          print_r($_POST['answers'][3]);
          foreach($_POST['answers'] as $_question_num=>$_users_answer)
          {
            $chkanswer=$this->checkanswer($_question_num);
            if($chkanswer['your_answer']==$chkanswer['correct_answer']){
              $total_correct_answers++;
            }
          }

          echo('<h2>'.(number_format(($total_correct_answers/$total_answers)*100, 0, '.', '')).'%</h2>
                <h3>You answered '.$total_correct_answers.' out of '.$total_answers.' questions correctly. <a href="">Try Again</a></h3>');
        }
        else
        {
          echo('Flash card set complete. <a href="">Click here to start over</a>.');
        }
      }
    }else{
      echo $this->quiz_error();
    }

  }
  function learning_mode_print_answer($question_num)
  {
    $chkanswer=$this->checkanswer($question_num);
    if($chkanswer['your_answer']==$chkanswer['correct_answer']){
      $colortext='00FF00';
    }else{
      $colortext='FF0000';
    }

    echo '<h4><b>PREVIOUS QUESTION:</b> '.$this->parsed_XML[$question_num]['text'].'</h4>
          <p style="color:#'.$colortext.';">
          <b>YOUR ANSWER:</b> '.$chkanswer['your_answer'].'
          <br>
          <b>THE CORRECT ANSWER:</b> '.$chkanswer['correct_answer'].'
          <br>
          <b>EXPLANATION:</b> '.$this->parsed_XML[$question_num]['explanation'].'
          </p>
          <hr>
         ';
  }
  function checkanswer($question,$your_answer=null)
  {
    if($this->parseXML($this->quizID.'.xml')!==false && $question>0)
    {
      $a=$this->parsed_XML[$question];
/*
      echo('<br>checkanswer:<pre>');
      print_r($a);
      echo('<br>');
      print_r($_POST);
      echo('</pre>');
*/
      if($your_answer===null){$your_answer='';}
      $correct_answer='';
      if($a['type']=='radio'){
        if($your_answer===''){$your_answer=$a['choice'.$_POST['answers'][$question]];}
        $correct_answer=$a['choice'.$a['answer']];
      }else if($a['type']=='blank'){
        if($your_answer===''){$your_answer=$_POST['answers'][$question];}
        $correct_answer=$a['choice'.$a['answer']];
      }else if($a['type']=='box'){
        $correct_answer_array=explode(',',$a['answer']);
        sort($correct_answer_array);
//        print_r($correct_answer_array);
        foreach($correct_answer_array as $key=>$value)
        {
          $correct_answer_array[$key]=$a['choice'.$value];
          $correct_answer.=$a['choice'.$value].' | ';
        }
        if($your_answer==='')
        {
          $your_answers=$_POST['answers'][$question];
          ksort($your_answers);
//          print_r($your_answers);
  //        die();
          $your_answers_array=array();
          foreach($your_answers as $key=>$value)
          {
            $your_answers_array[]=$a['choice'.$key];
            $your_answer.=$a['choice'.$key].' | ';
          }
          $your_answer=substr($your_answer,0,-3);
        }
        $correct_answer=substr($correct_answer,0,-3);
      }

      return array('your_answer'=>$your_answer,'correct_answer'=>$correct_answer);
    }
    return false;
  }
  function XML_startTag($parser, $data, $attr){
    if(strtolower($data)=='question'){
      $this->in_question++;
    }else{
      $this->in_section=strtolower($data);
    }
  }
  function XML_contents($parser, $data){
    if($this->in_question>0 && ($this->in_section=='text' || strpos($this->in_section,'choice')!==false || $this->in_section=='answer' || $this->in_section=='explanation' || $this->in_section=='type')){
      if($this->in_section=='answer'){$data=strtolower($data);}
      $this->parsed_XML[$this->in_question][$this->in_section]=$data;
    }
  }
  function XML_endTag($parser, $data){
    if(strtolower($data)=='question'){
//      $this->in_question++;
    }else{
      $this->in_section='';
    }
  }
  function parseXML($file)
  {
    if($this->parseXML_cache===null)
    {
      $file=str_replace('\\','/',$this->xml_url.'/'.$file);

      $this->in_question=0;
      $this->in_section='';

      $xml_parser=xml_parser_create();
      xml_set_object($xml_parser,$this);
      xml_set_element_handler($xml_parser,'XML_startTag','XML_endTag');
      xml_set_character_data_handler($xml_parser,'XML_contents');

      $fp=fopen($file,'r');
      $data=fread($fp, 80000);

      if(!(xml_parse($xml_parser, $data, feof($fp)))){
        $this->error='XML Document error on line '.xml_get_current_line_number($xml_parser);
        $this->parseXML_cache=false;
        return false;
      }
      xml_parser_free($xml_parser);
      fclose($fp);
      foreach($this->parsed_XML as $a=>$value){if(!isset($this->parsed_XML[$a]['type'])){$this->parsed_XML[$a]['type']='radio';}}

      $this->parseXML_cache=$data;
      return $data;
    }else{
      return $this->parseXML_cache;
    }
  }
  function quiz_error()
  {
    return $this->error;
  }
}

?>
and here is an example of the XML document:

Code: Select all

<?xml version="1.0"?>
<QUIZ>

<QUESTION>
<TEXT>Who was the fifth president of the United States?</TEXT>
<CHOICEA>James Monroe</CHOICEA>
<CHOICEB>James Madison</CHOICEB>
<CHOICEC>John Quincy Adams</CHOICEC>
<ANSWER>A</ANSWER>
<EXPLANATION>cause james rocks</EXPLANATION>
<TYPE>radio</TYPE>
</QUESTION>

<QUESTION>
<TEXT>What city is the capital of Maine?</TEXT>
<CHOICEA>Augusta</CHOICEA>
<ANSWER>A</ANSWER>
<EXPLANATION>It's just how things are</EXPLANATION>
<TYPE>blank</TYPE>
</QUESTION>

<QUESTION>
<TEXT>Which of these colors are not pink?</TEXT>
<CHOICEA>Green</CHOICEA>
<CHOICEB>Red</CHOICEB>
<CHOICEC>Pink</CHOICEC>
<ANSWER>A,B</ANSWER>
<EXPLANATION>becasue pink is pink and the others are not</EXPLANATION>
<TYPE>box</TYPE>
</QUESTION>

<QUESTION>
<TEXT>When was the US Constitution signed?</TEXT>
<CHOICEA>1789</CHOICEA>
<CHOICEB>1776</CHOICEB>
<CHOICEC>1787</CHOICEC>
<ANSWER>A</ANSWER>
<EXPLANATION>it's the facts of life</EXPLANATION>
</QUESTION>


</QUIZ>
First there is an error on the very first questions that goes away, but appears ever time the first question comes up:

Code: Select all

Warning: Invalid argument supplied for foreach() in /home/cristcdl/public_html/notc/class_quiz.inc.php on line 87
I know I can paste my header and footer in the index.php file however I would like for there to be an include to automatically include/parse the header and footer files into the index file. they would be txt or HTML files.

Now for what I think will be the hard part. This quiz works great but at the end only tells you how many you got right, out of how many questions there are. What I am looking for is for the final page to display every question, all of the options, the correct answer, and the users input of their answer. For example:

Question 1:

a. answer a
b. answer b
c. answer c

Correct answer: a. answer a
Your answer: b. answer b

Question 2:

a. answer a
b. answer b
c. answer c

Correct answer: c. answer c
Your answer: c. answer c

And so on for as many questions as there are in the test. So a complete final review.

Also the fact that this script does reload the page between every question is a mandatory must keep. It is the main reason I am looking to get help fixing this script to work the way I want versus using another script. If anyone can help me with this please let me know it would be greatly appreciated.

Please help this is very much in need for my new plans with website. I have looked everywhere and I am not able to find another script that is as close as to what I want as this one.

Thanks,
cristcdl
User avatar
Christopher
Site Administrator
Posts: 13596
Joined: Wed Aug 25, 2004 7:54 pm
Location: New York, NY, US

Re: Help with quiz code

Post by Christopher »

cristcdl wrote:What I am looking for is for the final page to display every question, all of the options, the correct answer, and the users input of their answer.
You probably want to save the user's answers in a session variable. Then at the end you can generate the remediation page.
(#10850)
cristcdl
Forum Newbie
Posts: 2
Joined: Sun Aug 10, 2014 6:18 pm

Re: Help with quiz code

Post by cristcdl »

Thank you for your reply, however I am not a php code programmer, and I an in need of help fixing this code to get rid of error and help to get the end page displayed the way I would like it. Can someone please help a little further with this code? Thank you! Needing as much help as I can get
Post Reply