Jump to content

Quiz results passing & displaying wrong.


davidc_38

Recommended Posts

Could anyone please help me figure out the errors in my code.


Error 1: When the user clicks 'quiz result' the selected answer on the final question isn't brought through to the quiz_results.php


Error 2: When the user clicks the correct answer on any question it isn't added to the rightAnswers and thus their results display 'Correct answers: 0;'


quiz.php:



<?php
if(isset($_POST['checkQuiz'])) {
$a=$_POST['a'];

$quiz_id=$_SESSION['quiz_id'];
$index=$_SESSION['index'];

$resultQuery = mysqli_query($con,"SELECT `correctValue` FROM quiz_questions WHERE quiz_id = '$quiz_id' LIMIT 1 OFFSET $index");
$cor=0;
$incorrect=0;

while ($correct = mysqli_fetch_array($resultQuery))
{
if ($_POST['answer'] == $correct[0]) {
$_SESSION['rightAnswers']+=1;
}

if ($_POST['answer'] != $correct[0]) {
$_SESSION['wrongAnswers']+=1;
}
}

}
if(isset($_POST['checkResult'])) {
$a=$_POST['a'];

//quiz variables
$quiz_id=$_SESSION['quiz_id'];
$index=$_SESSION['index'];

//query to get correct answet for current question
$resultQuery = mysqli_query($con,"SELECT `correctValue` FROM quiz_questions WHERE quiz_id = '$quiz_id' LIMIT 1 OFFSET $index");
$cor=0;
$incorrect=0;

//while loop for correct answer
while ($correct = mysqli_fetch_array($resultQuery))
{
//if radio button check correct add 1 to right answers
if ($_POST['answer'] == $correct[0]) {
$_SESSION['rightAnswers']+=1;
}
// if not correct add 1 to wrong answers
if ($_POST['answer'] != $correct[0]) {}
$_SESSION['wrongAnswers']+=1;
}
}
if($a==$_SESSION['numberOfQuestions']){
header("Location: quiz_result.php");
}

}
//score 0 id $a not set
if(!isset($a)){
$a=0;
$_SESSION['rightAnswers']=0;
$_SESSION['wrongAnswers']=0;
}

$quiz_id = $_GET['quiz_id'];
$_SESSION['index']=$a;
$questionNumber = $a+1;

$_SESSION['quiz_id']=$quiz_id;
$numberOfQuestionsQuery = mysqli_query($con, "SELECT COUNT(quiz_id) AS numberOfQuestions FROM quiz_questions WHERE quiz_id ='$quiz_id'");
$numberOfQuestionsResult = mysqli_fetch_object($numberOfQuestionsQuery);

$_SESSION['numberOfQuestions']=$numberOfQuestionsResult->numberOfQuestions;
$numberQuizQuestions=$_SESSION['numberOfQuestions'];

$get_questions = mysqli_query($con,"SELECT * FROM `quiz_questions` WHERE `quiz_id` = '$quiz_id' LIMIT 1 OFFSET $a");
while ($result = mysqli_fetch_array($get_questions)) { ?>

<form id="question_no" ><div class="left"></div> <div class="right">No. of questions: <?php echo $numberQuizQuestions; ?> </div> </form> <br> <br><br>
<form method="post" action="" class="form complete">
<table>
<td>
<td width = "50" id="question"><?php echo $result['question'] . "<br>"; ?></td>
</td>

<tr height = "10"></tr>

<td id= "number" width = "20" class="number"><?php echo $questionNumber ?>)</td>
<td id = "possible_answers" height = "100"width = "700">
<input type="radio" name="answer" value="<?php echo $result['answerA'] ?>"> <?php echo $result['answerA']; ?> <br>
<input type="radio" name="answer" value="<?php echo $result['answerB'] ?>"> <?php echo $result['answerB']; ?> <br>
<input type="radio" name="answer" value="<?php echo $result['answerC'] ?>"> <?php echo $result['answerC']; ?> <br>
<input type="radio" name="answer" value="<?php echo $result['answerD'] ?>"> <?php echo $result['answerD']; ?> <br><br> </td>
</table>
<?php
$_SESSION['questionNumber']=$questionNumber;
}
$a=$a+1;
?>
<a href="interactive_training.php" id="button1">« Back to training</a>

<?php //next question if less than number of questions
if ($questionNumber<$_SESSION['numberOfQuestions']) {

?>
<input type="submit" name="checkQuiz" value="Next Question" id="button1">
<input type="hidden" value="<?php echo $a ?>" name="a">
<?php } ?>

<?php //check results = end of quiz
if ($questionNumber==$_SESSION['numberOfQuestions'])
{ ?>
<a type="submit" href = "quiz_result.php?session_id=<?php echo $_GET['session_id']; ?>" name="checkResult" id="button1"> Quiz Result </a>
<?php } ?>

quiz_results.php



<div class="result">Result</div> <hr> <br>

<?php

include("includes/database.php");

$currentUserID = $_SESSION['currentUserID'];
$session_id = $_GET['session_id'];


$correct = $_SESSION['rightAnswers'];
$questions = $_SESSION['questionNumber'];
$percent = $correct/$questions;
$percent_friendly = number_format( $percent * 100, 0 ) . '%';
$_SESSION['percent']=$percent_friendly;
?>

<form>
<div><input class="result" Value ="Quiz ID:- <?php echo $_SESSION['quiz_id'];?>" readonly> </div><br>
<div><input class="result" Value ="Questions Answered:- <?php echo $_SESSION['questionNumber'];?>" readonly> </div><br>
<div><input class="result" Value ="Correct Answers:- <?php echo $_SESSION['rightAnswers'];?>" readonly> </div><br>
<div><input class="result" Value ="Incorrect Answers:- <?php echo $_SESSION['wrongAnswers'];?>" readonly> </div><br>
<div><input class="result" Value ="Result Percentage:- <?php echo $_SESSION['percent'];?>" readonly> </div><br>

<hr>

Any help would be greatly apprecaited 


 


Link to comment
Share on other sites

You need to start a session top of each script

 

session_start();

 

http://php.net/manual/en/session.examples.basic.php

Hi QuickOldCar,

 

I have session_start at the top of each script, I just pasted the code which I thought would be the most useful. Really can't work out what it is going on, could any of your expertise shed light? Does my while loop seem ok? Thanks

Link to comment
Share on other sites

Maybe this will shed some light on your problem:

    <form id="trivia_quiz" action="<?php echo $basename; ?>" method="post">
        <?php
        $counter = 1;
        foreach ($_SESSION['daily_questions'] as $key => $value) {
            if (strlen($counter) < 2) {
                $counter = "0" . $counter;
            }
            echo "<h1 class=\"question\">" . $counter . ". " . $value['question'] . "</h1>\n";
            echo '<div class="answers"><input id="button' . $key . '_1" type="radio" name="answer[' . $key . ']" value="1"><label for="button' . $key . '_1">' . $value['answer1'] . '</label>' . "</div>\n";
            echo '<div class="answers"><input id="button' . $key . '_2" type="radio" name="answer[' . $key . ']" value="2"><label for="button' . $key . '_2">' . $value['answer2'] . '</label>' . "</div>\n";
            echo '<div class="answers"><input id="button' . $key . '_3" type="radio" name="answer[' . $key . ']" value="3"><label for="button' . $key . '_3">' . $value['answer3'] . '</label>' . "</div>\n";
            echo '<div class="answers"><input id="button' . $key . '_4" type="radio" name="answer[' . $key . ']" value="4"><label for="button' . $key . '_4">' . $value['answer4'] . '</label>' . "</div><br><hr><br>\n";
            $counter += 1;
        }
        ?>
        <input type="submit" name="submit" value="submit">
    </form>

I find reading 10 questions in at a time and spitting them out at once is the easiest or you can use JavaScript (I use jQuery) to have only one question displayed at a time. Though there are many ways of doing it.  

Link to comment
Share on other sites

Maybe this will shed some light on your problem:

    <form id="trivia_quiz" action="<?php echo $basename; ?>" method="post">
        <?php
        $counter = 1;
        foreach ($_SESSION['daily_questions'] as $key => $value) {
            if (strlen($counter) < 2) {
                $counter = "0" . $counter;
            }
            echo "<h1 class=\"question\">" . $counter . ". " . $value['question'] . "</h1>\n";
            echo '<div class="answers"><input id="button' . $key . '_1" type="radio" name="answer[' . $key . ']" value="1"><label for="button' . $key . '_1">' . $value['answer1'] . '</label>' . "</div>\n";
            echo '<div class="answers"><input id="button' . $key . '_2" type="radio" name="answer[' . $key . ']" value="2"><label for="button' . $key . '_2">' . $value['answer2'] . '</label>' . "</div>\n";
            echo '<div class="answers"><input id="button' . $key . '_3" type="radio" name="answer[' . $key . ']" value="3"><label for="button' . $key . '_3">' . $value['answer3'] . '</label>' . "</div>\n";
            echo '<div class="answers"><input id="button' . $key . '_4" type="radio" name="answer[' . $key . ']" value="4"><label for="button' . $key . '_4">' . $value['answer4'] . '</label>' . "</div><br><hr><br>\n";
            $counter += 1;
        }
        ?>
        <input type="submit" name="submit" value="submit">
    </form>

I find reading 10 questions in at a time and spitting them out at once is the easiest or you can use JavaScript (I use jQuery) to have only one question displayed at a time. Though there are many ways of doing it.  

 

I will look into this, thanks! It seems the quiz_results.php page is static and no matter what you choose answer-wise, the results remain the same. It's not necessarily needed to have the questions on separate pages, in fact if I can have them all on the one page this would be more desirable, do you think this would be easier? Thanks for your help

Link to comment
Share on other sites

If you have all the questions on one page then name your radio buttons something like "answer[$id]" where $id is the id of the question. Then if you answer B for Q1, C for Q2 and D for Q3 then $_POST['answer'] will look like this when you come to process the results

array (
  1 => 'B'
  2 => 'C'
  3 => 'D'
)

All you need to do then is get the correct answers from the database for each question and compare.

 

Here's an example

<?php
$db = new mysqli(HOST,USERNAME,PASSWORD,'dbname');

$correct = array();
/************************************************
* if answers posted, check them
*************************************************/
if ($_SERVER['REQUEST_METHOD']=='POST') {
    $sql = "SELECT question_no
            , correct_answer
            FROM quiz_questions";
    $res = $db->query($sql);
    while ($row = $res->fetch_assoc()) {
        $correct[$row['question_no']] = $row['correct_answer'];
    }
    // get the posted answers and compare aginst correct ones
    $total = 0;
    if (isset($_POST['answer']))
        foreach ($_POST['answer'] as $qno => $ans) {
            if ($ans == $correct[$qno]) {
                $total++;
            }
        }
    echo "You got $total answers correct<br>";
}

$sql = "SELECT question_no
        , question
        , answerA
        , answerB
        , answerC
        , answerD
        FROM quiz_questions
        ORDER BY question_no";
$output = '';
$res = $db->query($sql);
while (list($qno,$q, $a, $b, $c, $d) = $res->fetch_row()) {
    $output .= "<div class='wrapper'>
            <div class='question'>$qno. $q</div>
            <div class='answers'>
            <input type='radio' name='answer[$qno]' value='A'>$a<br>
            <input type='radio' name='answer[$qno]' value='B'>$b<br>
            <input type='radio' name='answer[$qno]' value='C'>$c<br>
            <input type='radio' name='answer[$qno]' value='D'>$d<br>
            </div>
            <div style='clear:both'></div>
            </div>";
}
?>
<html>
<head>
<title>Quiz</title>
<style type='text/css'>
div {
    font-family: sans-serif;
    font-size: 10pt;
}
.wrapper {
    border-bottom: 2px solid gray;
    padding: 5px;
    margin-bottom: 5px;
    height: auto;
}
.question {
    width: 40%;
    float: left;
}
.answers {
    width: 60%;
    float: left;
}

</style>
</head>
<body>
<h3>Quiz</h3>
<form method='post' action=''>
<?=$output?>
<input type='submit' name='btnSubmit' value='Results'>
</form>
</body>
</html>


It would be a better design to have your answers in a separate table, each row containing

question_id || option value || answer_text
Edited by Barand
  • Like 1
Link to comment
Share on other sites

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.