Register

If this is your first visit, please click the Sign Up now button to begin the process of creating your account so you can begin posting on our forums! The Sign Up process will only take up about a minute of two of your time.

Results 1 to 8 of 8
  1. #1
    Junior Member
    Join Date
    Sep 2014
    Posts
    5
    Member #
    40310

    PHP multi choice quiz- how to show 20 random questions out of 80 questions

    Hi guys. I'm Rich and only just joined this forum. I hope that you can help me please as I'm ready to rip my hair out!

    At the moment I'm re-creating the website that I designed for my dissertation while I was at uni. This is also going to be my portfolio to show employers my skills and knowledge which will help me to get a graduate PHP web developer job. Over the past few weeks I have had a number of job offers but they cannot offer me an interview untill I have my website up and running and on a web domain.

    The webs site is a learning aid for people like myself who have the learning disability called dyscalculia. There are revision pages that are now complete. I have got a quiz with 80 questions. I would like to be able to show just 20 questions that are random.

    This is the quiz code so far:
    PHP Code:
      <head>
        <link rel="stylesheet" type="text/css" href="/css/style.css" />
    </head>
    <?php
    require 'core/init.php';
    include(
    'inc/pheader.php'); ?>

    <?php

    session_start
    ();
    if(isset(
    $_GET['question'])){
        
    $question preg_replace('/[^0-9]/'""$_GET['question']);
        
    $next $question 1;
        
    $prev $question 1;
        if(!isset(
    $_SESSION['qid_array']) && $question != 1){
            
    $msg "Sorry! No cheating.";
            
    header("location: start.php?msg=$msg");
            exit();
        }
        if(isset(
    $_SESSION['qid_array']) && in_array($question$_SESSION['qid_array'])){
            
    $msg "Sorry, Cheating is not allowed. You will now have to start over. Haha.";
            unset(
    $_SESSION['answer_array']);
            unset(
    $_SESSION['qid_array']);
            
    session_destroy();
            
    header("location: start.php?msg=$msg");
            exit();
        }
        if(isset(
    $_SESSION['lastQuestion']) && $_SESSION['lastQuestion'] != $prev){
            
    $msg "Sorry, Cheating is not allowed. You will now have to start over. Haha.";
            unset(
    $_SESSION['answer_array']);
            unset(
    $_SESSION['qid_array']);
            
    session_destroy();
            
    header("location: start.php?msg=$msg");
            exit();
        }
    }
    ?>
    <!doctype html>
    <html>
    <head>
    <meta charset="utf-8">
    <title>Quiz Page</title>
    <script type="text/javascript">
    function countDown(secs,elem) {
        var element = document.getElementById(elem);
        element.innerHTML = "You have "+secs+" seconds remaining.";
        if(secs < 1) {
            var xhr = new XMLHttpRequest();
            var url = "userAnswers.php";
                var vars = "radio=0"+"&qid="+<?php echo $question?>;
                xhr.open("POST", url, true);
                xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
                xhr.onreadystatechange = function() {
            if(xhr.readyState == 4 && xhr.status == 200) {
                alert("You did not answer the question in the allotted time. It will be marked as incorrect.");
                clearTimeout(timer);
        }
    }
    xhr.send(vars);
            document.getElementById('counter_status').innerHTML = "";
            document.getElementById('btnSpan').innerHTML = '<h2>Times Up!</h2>';
            document.getElementById('btnSpan').innerHTML += '<a href="quiz.php?question=<?php echo $next?>">Click here now</a>';

        }
        secs--;
        var timer = setTimeout('countDown('+secs+',"'+elem+'")',1000);
    }
    </script>
    <script>
    function getQuestion(){
        var hr = new XMLHttpRequest();
            hr.onreadystatechange = function(){
            if (hr.readyState==4 && hr.status==200){
                var response = hr.responseText.split("|");
                if(response[0] == "finished"){
                    document.getElementById('status').innerHTML = response[1];
                }
                var nums = hr.responseText.split(",");
                document.getElementById('question').innerHTML = nums[0];
                document.getElementById('answers').innerHTML = nums[1];
                document.getElementById('answers').innerHTML += nums[2];
            }
        }
    hr.open("GET", "questions.php?question=" + <?php echo $question?>, true);
      hr.send();
    }
    function x() {
            var rads = document.getElementsByName("rads");
            for ( var i = 0; i < rads.length; i++ ) {
            if ( rads[i].checked ){
            var val = rads[i].value;
            return val;
            }
        }
    }
    function post_answer(){
        var p = new XMLHttpRequest();
                var id = document.getElementById('qid').value;
                var url = "userAnswers.php";
                var vars = "qid="+id+"&radio="+x();
                p.open("POST", url, true);
                p.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
                p.onreadystatechange = function() {
            if(p.readyState == 4 && p.status == 200) {
                document.getElementById("status").innerHTML = '';
                alert("Thanks, Your answer was submitted"+ p.responseText);
                var url = 'quiz.php?question=<?php echo $next?>';
                window.location = url;
        }
    }
    p.send(vars);
    document.getElementById("status").innerHTML = "processing...";

    }
    </script>
    <script>
    window.oncontextmenu = function(){
        return false;
    }
    </script>
    </head>

    <body onLoad="getQuestion()">
    <div id="status">
    <div id="counter_status"></div>
    <div id="question"></div>
    <div id="answers"></div>
    </div>
    <script type="text/javascript">countDown(45,"counter_status");</script>
    </body>
    </html>
    Any help would be much appreciated

    Thanks guys

    Rich

  2.  

  3. #2
    WDF Staff mlseim's Avatar
    Join Date
    Apr 2004
    Location
    Cottage Grove, Minnesota
    Posts
    7,686
    Member #
    5580
    Liked
    716 times
    Can you post "questions.php", and post a link to your web page so I can see the test in action?

    If you can't do this in public, private message me.


  4. #3
    Junior Member
    Join Date
    Sep 2014
    Posts
    5
    Member #
    40310
    hey thanks for the replay its much appreciated.

    This is the questions.php

    PHP Code:
    <head>
        <link rel="stylesheet" type="text/css" href="/css/style.css" />
    </head>
    <?php
    require 'core/init.php';
    include(
    'inc/pheader.php'); 


    session_start();
    require_once(
    "scripts/scriptsconnect_db.php");
    $arrCount "";
    if(isset(
    $_GET['question'])){
        
    $question preg_replace('/[^0-9]/'""$_GET['question']);
        
    $output "";
        
    $answers "";
        
    $q "";
        
    $sql mysql_query("SELECT id FROM questions");
        
    $numQuestions mysql_num_rows($sql);
        if(!isset(
    $_SESSION['answer_array']) || $_SESSION['answer_array'] < 1){
            
    $currQuestion "1";
        }else{
            
    $arrCount count($_SESSION['answer_array']);
        }
        if(
    $arrCount $numQuestions){
            unset(
    $_SESSION['answer_array']);
            
    header("location: start.php");
            exit();
        }
        if(
    $arrCount >= $numQuestions){
            echo 
    'finished|<p>There are no more questions. Please enter your first and last name and click next</p>
                    <form action="userAnswers.php" method="post">
                    <input type="hidden" name="complete" value="true">
                    <input type="text" name="username">
                    <input type="submit" value="Finish">
                    </form>'
    ;
            exit();
        }
        
    $singleSQL mysql_query("SELECT * FROM questions WHERE id='$question' ORDER BY rand() LIMIT 20;");
        
    //$singleSQL = mysql_query("SELECT * FROM questions WHERE id='$question' LIMIT 1");
            
    while($row mysql_fetch_array($singleSQL)){
                
    $id $row['id'];
                
    $thisQuestion $row['question'];
                
    $type $row['type'];
                
    $question_id $row['question_id'];
                
    $q '<h2>'.$thisQuestion.'</h2>';
                
    $sql2 mysql_query("SELECT * FROM answers WHERE question_id='$question' ORDER BY rand()");
                while(
    $row2 mysql_fetch_array($sql2)){
                    
    $answer $row2['answer'];
                    
    $correct $row2['correct'];
                    
    $answers .= '<label style="cursor:pointer;"><input type="radio" name="rads" value="'.$correct.'">'.$answer.'</label> 
                    <input type="hidden" id="qid" value="'
    .$id.'" name="qid"><br /><br />
                    '
    ;
                    
                }
                
    $output ''.$q.','.$answers.',<span id="btnSpan"><button onclick="post_answer()">Submit</button></span>';
                echo 
    $output;
               }
            }
        

    ?>
    At the moment my website is not live and I'm running it on my local host via xampp. All of the questions are in my database that im using through phpmyadmin

  5. #4
    Junior Member
    Join Date
    Sep 2014
    Posts
    5
    Member #
    40310
    the quiz works perfect. I just want to have 20 questions showing at random, once I have got this sorted. I then want to have a personal profile that shows each quiz a particular user has taken, how many answers they have got correct or they have got wrong. (There is a personal log in for each user that is working too)

  6. #5
    WDF Staff mlseim's Avatar
    Join Date
    Apr 2004
    Location
    Cottage Grove, Minnesota
    Posts
    7,686
    Member #
    5580
    Liked
    716 times
    There's not enough information provided for me to know how your script is set-up.

    It looks like you have two MySQL tables, one for 'questions' and one for 'answers'.
    Why is there two tables for 'questions' and 'answers'? Wouldn't that be one table?

    How do you know which questions go with which answers?

    I assume both tables have an 'id' of some kind that relates a question to an answer? If so, the two tables can be joined when you do a query. So that is where I'm stuck ... and also have other questions ... are you correcting them and scoring as they go? Is it done with PHP or javascripting? Do you only need to know how many correct and how many wrong, or exactly which specific questions were wrong?

    When someone views the HTML, can they see the question answer? This would be related to the javascript questions I have.

    It almost seems like you're making it harder than it needs to be.

    That's why I want to actually see the working website and take a test myself, to see how the scripting is operating.


  7. #6
    Junior Member
    Join Date
    Sep 2014
    Posts
    5
    Member #
    40310
    hey i will have to private message you. just about going to work

  8. #7
    Junior Member
    Join Date
    Sep 2014
    Posts
    5
    Member #
    40310
    Quote Originally Posted by mlseim View Post
    There's not enough information provided for me to know how your script is set-up.

    It looks like you have two MySQL tables, one for 'questions' and one for 'answers'.
    Why is there two tables for 'questions' and 'answers'? Wouldn't that be one table?

    How do you know which questions go with which answers?

    I assume both tables have an 'id' of some kind that relates a question to an answer? If so, the two tables can be joined when you do a query. So that is where I'm stuck ... and also have other questions ... are you correcting them and scoring as they go? Is it done with PHP or javascripting? Do you only need to know how many correct and how many wrong, or exactly which specific questions were wrong?

    When someone views the HTML, can they see the question answer? This would be related to the javascript questions I have.

    It almost seems like you're making it harder than it needs to be.

    That's why I want to actually see the working website and take a test myself, to see how the scripting is operating.
    Hey mate. sorry it has taken so long to replay back to you. I have just been so busy my mum has been so ill.

    Right ok I had the code from this website GotCode.org | Learn Programming free, online and fast I've posted on the forums and no one seems to be helping as there are not many members. There are youtube videos that are very very helpful

    You asked about the tables, one is called "answers" and the other is called "questions" both are related/ linked as they have ID and question ID. So this is so the answers and questions can be linked along with what answer the user is regustering when taking the quiz. This is done with PHP

    Hope yu can help me

  9. #8
    WDF Staff mlseim's Avatar
    Join Date
    Apr 2004
    Location
    Cottage Grove, Minnesota
    Posts
    7,686
    Member #
    5580
    Liked
    716 times
    There will need to be other tables that keep track of each user, and which 20 questions they are randomly given.

    Basically, you will use your existing questions and answers table as your "master" tables.
    One table is called "questions" and the other "answers", just as it is now.
    You enter all of your questions and answers just as you do now ... nothing changes with that.
    Your master tables might end-up with 500 questions ... it doesn't matter.

    Now you have to give each user a set of 20 random questions ...

    When someone takes a test, they log-in. Let's say their user ID is "23".
    A PHP script will randomly take 20 questions out of the "questions" table.
    The PHP script will create a new questions table using the user's ID ... example "questions_23".
    The PHP script will then create a new answers table using the same 20 questions and the user's ID ... example "answers_23".

    When any user logs in, they are served the test just like your script does now, but it uses their own tables, not the master tables.
    Each user will have a test with 20 questions, and the test will be different for each user.

    You will end-up with many tables, two for each user.
    But as they finish the test and that 3rd table (the one the script author is using) is used to keep score, you can "drop" the student's tables.

    If a student logs-in to take another test and their are no tables assigned to their user ID, two new tables are create (the process starts over again).

    When any student logs-in, I assume a SESSION variable is set, that contains their student ID. The PHP scripts will always access the correct tables by looking at the SESSION variable of the person using the site.

    By adding new columns, such as a timestamp, you can control how long, or how often a test can be taken, or a test can be continued if a student does 10 questions and exits their browser. Can they log back in and finish? Can they only do that within an hour, or a day? Timestamps will update each time a question gets answered. The scripting possibilities here are infinite, depending on your rules for taking tests.

    Let's pretend a student is given a test of 20 questions and they "bail out" at question 18. Now they leave your site and never return. Their two tables are stuck in your database. By having a timestamp column, you can "drop" any tables that are over 7 days old. That will keep your database clean of non-completed tests.

    It would be necessary to also keep track of the students answers for each question. As it is now, the script you have doesn't "save" the answers the student gives in a database. If they answer 5 questions and quit, they have to start all over again when they return. You'll need to keep track of which questions they answer, and what their answers are.

    Doing the actual scripting is another issue. It will involve rewriting/modifying all of the scripts they provided.

    That's my solution.

    NOTE:
    If you hire a programmer and agree my solution is viable, you can simply show them this thread.
    In reality, you should be doing it yourself, to learn it, and prove your skills.




    .
    Last edited by mlseim; Oct 15th, 2014 at 05:28 PM.



Remove Ads

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  

Search tags for this page

exam question randomly with php
,
exam with random question codes php
,
online quiz javascript code with 20 question random with output with time limit
,
online quiz that select random question from database and check thier answers
,

php code that can out up a quiz

,
php quiz random questions
,
ramdom exam on phpmyadmin
,
random questionnaire in php
,
randomized quiz code in php
Click on a term to search for related topics.
All times are GMT -6. The time now is 05:04 PM.
Powered by vBulletin® Version 4.2.3
Copyright © 2019 vBulletin Solutions, Inc. All rights reserved.
vBulletin Skin By: PurevB.com