Stetchy Stetchy - 3 months ago 12
MySQL Question

PHP session variable only increments once

I've been fiddling with PHP recently along with databases and I've come across a problem where I when I want to increment a session variable, question_id within an if statement it will increment once and not increment thereafter.

$_SESSION['question_id'] = 11; // Set default var

if(isset($_POST['ans'])) {
if($funcs->checkAnswer($_SESSION['question_id'], $mysqli)) {
$_SESSION['question_id'] = $_SESSION['question_id'] + 1;

$question = $funcs->getQuestion($_SESSION['question_id'], $mysqli);

The $_POST variable ans is the ID of a form where the user puts their answer, this answer is checked against the correct answer in the database by checkAnswer() which grabs the correct answer and compares it to the users' answer, if correct it returns true, else false. If checkAnswer() is true, in theory the session variable question_id should increment each time and thus update the question, however it does this only once then after this it stays on the first iteration of the increment (question 2), and if the answer inputted by the user is wrong, it resets back to question one for some reason.

Does anyone know why the $_SESSION['question_id'] only increments once even though the if statement is true? If you can see where the reset problem lies also that'd be great but I'll probably create a new post for that.

Thanks in advance.


You always reset your question_id to 11. You have to write:

if (empty($_SESSION['question_id']) {
    $_SESSION['question_id'] = 11;