0

Morning guys hope that you are all well. need to pick your brains because I'm ready to bang my head against a brick wall.

I'm building a multipolchoice quiz I want to just show 20 random questions from the 80 questions that I have in the question bank, in my database. Its split in to 3 tables
- answers
- questions
- user answers

Everytime I run the quiz, the quiz just keeps showing all 80 questions from question 1 through to question 80, I actully want it to just rum 20 questions in a ramdom way everytime the user takes the quiz, any ideas how I can get this sorted?

Below is the code so far

<?php

$mysql = mysql_query  ("select * from questions order by rand() limit 0,20");


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: index.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: index.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: index.php?msg=$msg");
        exit();
    }
}
?>

Any help would be brillaint as this is delaying my site from going live andstopping me from applying for a job

Rich

2
Contributors
12
Replies
41
Views
2 Years
Discussion Span
Last Post by stokie-rich
0

yes that is all of the code

this is the other code to start the quiz

<?php 

$msg = "";
if(isset($_GET['msg'])){
    $msg = $_GET['msg'];
    $msg = strip_tags($msg);
    $msg = addslashes($msg);
}
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Quiz Tut</title>
<script>
function startQuiz(url){
    window.location = url;
}
</script>
</head>
<body>
<?php echo $msg; 
$question_id = rand(1, 20); ?>
<h3>Click below when you are ready to start the quiz. This is a ramdom quiz so each time you take the quiz the questions will show in a different order each time!</h3>

<button onClick="startQuiz('quiz.php?question=1')">Click Here To Begin</button>


</body>
</html>
0

You send question=1 to your script. That is an indication that you should select your 20 random questions (which your query does). You should only do that if you are on the first question. Next is that you need to store your 20 random questions in a session, so you can retrieve them when the next question is requested. So start there, retrieve the query results and store them in a session array for later retrieval.

0

hey pritaeas thanks so much for the feeback. I did actully have a funny feeling if it had something to do with the "start of quiz" code. I dont want anyone to do it for me but if anyone can give me some pointers how I can do this that would be brilliant not really done much with sessions before

0

right ok but the problem is with that then, everytime the user takes the quiz they will be answering the same questions. Thats the whole point why i want each time the user takes the quiz they answer 20 different ramdom questions so they dont know what questions will come up

0

No. You fill the session array only when the first question is requested. So even if the session exists, returning to question one will generate a new set.

0

ohh right sorry i get carried away i should of read your replay a little better... stupid stupid idiot that iam ignor me! I will take a look at this tomorrow and see how i get on with it and get back to you

0

A friend from work has helped me to develop this, built both functions w/ the question count as a variable, so the function can be called with a number other than the default 20. If 20 is going to be the count guaranteed, you can remove all this to appear like:

function fetchQuestions() {
  $stmt = $conn->prepare("SELECT `question` FROM `questions` ORDER BY RAND() LIMIT 20");
  $stmt->execute();
  $stmt->bind_result($result); 
  while ($stmt->fetch()) {
    $question[] = $result;
  }
  $stmt->close(); }

this is the whole of the quiz code now

<?php


function fetchQuestions() {
  $stmt = $conn->prepare("SELECT `question` FROM `questions` ORDER BY RAND() LIMIT 20");
  $stmt->execute();
  $stmt->bind_result($result); 
  while ($stmt->fetch()) {
    $question[] = $result;
  }
  $stmt->close(); }

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: index.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: index.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: index.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(30,"counter_status");</script>

</body>
</html>

But its still showing question 1 all the way through to question 80 can anyone give me some insight into why this is still happening?

0

Can you show the table structure for your questions table? I'd have to get it running, hard to tell from just the code.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.