vendredi 21 février 2020

The score is not being set correctly?

I am almost at the end of creating a basic quiz application. As a new programmer, I know that I will make lots of mistakes but I want to learn from them. So I have been getting a few hiccups and the latest one is that my score variable is not being set correctly.

I am getting zero mostly for the result score at the end of the quiz.

I don't know what the errors are. This is why I will be very grateful for any help or suggestions. Thank you very much indeed.

Here is a basic run through of my code:

#Question.php
<?php include "database.php"; 
?>
<?php session_start(); ?>

<?php
//Set question
$number = (int) $_GET['n'];


    /*
 * Get Total Questions
*/
 $query="SELECT * FROM questions" ;
 //Get Results
$results = mysqli_query ($conn,$query);
$total = mysqli_num_rows($results);



/*
* Get the Question
*/
$query = "SELECT * FROM questions
WHERE question_number = $number";

//Get result
$result = mysqli_query ($conn,$query);

$question = $result->fetch_assoc();


/*
* Get choices
*/
$query = "SELECT * FROM choices
WHERE question_number = $number";

//Get result
$choices = mysqli_query($conn,$query);


?>

 <?php echo $question ['text']; ?>
</p>
 <form method="post" action="process.php"
  <ul class="choices">

<?php while ($row = $choices->fetch_assoc()) : ?>
<li><input name="choice" type="radio" value="<?php echo $row ['id'];?> " /><?php echo $row ['text']; ?></li>
      <input type="submit" name="submit" value="Sumbit"/>
      <input type="hidden" name= "number" value="<?php echo $number; ?>" />



 </main>

    </body>
</html>

<?php endwhile; ?>

#Process.php
<?php include "database.php"; 
?>
<?php session_start(); ?>
<?php
// check to see if score is set error_handler)
if(!isset($_SESSION['score'] )) {
    $_SESSION ['score'] = 0;
}   

if($_POST) {
    $number = $_POST['number'];
    $selected_choice = $_POST['choice'];
    $next = $number+1;


    /*
 * Get Total Questions
*/
 $query="SELECT * FROM questions" ;
 //Get Results
$results = mysqli_query ($conn,$query);
$total = mysqli_num_rows($results);



    /*
    *   Get correct choice
    */
    $query = "SELECT * FROM choices
 WHERE question_number = $number AND is_correct=1";

//Get result
$result = mysqli_query($conn,$query);

//Get Row
$row = $result->fetch_assoc(); 

//Set Correct choice
$correct_choice = $row['id'];


//Compare choice
if ($correct_choice == $selected_choice) {
    //The answer is correct
    $_SESSION['score']+1 ;
}

//Check if it is the last question
if($number == $total){
    header("Location: final.php") ;
    exit();
    }  
    else { 
      header("Location: question.php?n=".$next);

    }

<p>Final score: <?php echo $_SESSION ['score']; ?> <p>



Aucun commentaire:

Enregistrer un commentaire