Reputation: 17
I am coding an online quizzer using PHP. Whenever the answerer of the quiz choose the correct answer, the code will automatically +1 to his overall score.
To do that, I used $_SESSION['score']=0;
to first set the score to zero and $_SESSION['score']++;
whenever the answerer gets the answer correct for each question.
However, I have no idea why the score is not adding up despite the answerers answering the questions correctly.
When the answerer answers the question correctly, the score is still 0 for some reason and I have no idea why. May I know what went wrong? Thank you.
Things I have tried:
1.Changing $_SESSION['score']++;
to $_SESSION['score']+1;
2.Changing:
if(!isset($_SESSION['score'])){
$_SESSION['score']=0;
}
to just
$_SESSION['score']=0;
3.Changing
if($correct_choice == $selected_choice){
$_SESSION['score']++;
}
to just:
if($correct_choice = $selected_choice){
$_SESSION['score']++;
}
Below is the code for process.php:
<?php include 'database.php'; ?>
<?php session_start(); ?>
<?php
if(!isset($_SESSION['score'])){
$_SESSION['score']=0;
}
if(isset($_POST['submit'])){
$number=$_POST['number'];
$selected_choice = $_POST['choice'];
$next=$number+1;
/*
* Get total questions
*/
$query="SELECT* FROM questions";
$results= mysqli_query($con,$query);
$total=$results->num_rows;
/*
* Get correct choice
*/
$query = "SELECT* FROM `choices` WHERE question_number = $number AND is_correct=1";
//Get result
$results= mysqli_query($con,$query);
//Get row
$row=$results->fetch_assoc();
//Set Correct choices
$correct_choice=$row['id'];
//Compare choice made with correct choice
if($correct_choice == $selected_choice){
$_SESSION['score']++;
}
//Check if last question
if($number == $total){
header("Location: final.php");
exit();
} else {
header("Location: question.php?n=".$next);
}
}
Just tried something:
if($correct_choice == $selected_choice){
echo "same";
} else{
echo "not same";
}
Even though $correct_choice
and $selected_choice
are both equals to 1, the code still returns as "not same"?
Upvotes: 0
Views: 106
Reputation:
Make sure that your code does not output anything to the browser before session_start() is called.
you can find more information about $_SESSION superglobal here.
To use cookie-based sessions, session_start() must be called before outputing anything to the browser.
Upvotes: 1
Reputation: 35169
You are opening and closing a lot of PHP tags - unnecessarily. If you have error reporting on, and being displayed on screen, it would likely be saying 'headers already sent'. That, is likely the issue.
Since the process.php file is all php - just open the <?php
tag once - and don't even bother to close it at the end - unless you are explicitly outputting something (which is bad practice anyway for a larger program, better to use a small framework, and separate templates).
Upvotes: 2