Search code examples
phpsession-variablessession-state

In a php session


}

put returns between paragraphs for linebreak add 2 spaces at end italic or bold indent code by 4 spaces backtick escapes like _so_ quote by placing > at start of line to make links (use https whenever possible)


Solution

  • You could have another session that stores the answers as an array, and add to it after each successful post

    Something like this could work:

     <?php
        $totalQuestions = count($ques);
        $_SESSION['answers'] = $_SESSION['answers'] ?? [];
        // Get current question, default to 1
        $currentQuestion = count($_SESSION['answers']) == $totalQuestions ? 
            $totalQuestions : 
            $_SESSION['answers'] + 1;
    ?>
    
    <div class='questionHeader'>
        <label>Question <?php echo $currentQuestion ?> of <?php echo $totalQuestions ?></label>
    </div>
    
    <br>
    
    <div class='question'>
        <?php echo $ques[$currentQuestion-1] ?>
    </div>
    
    Answer: <input type='text' id='answerOneSub' name='answerOneSub'>
    <button type='submit' value='submit' name='submit'>Submit!</button>
     
    <?php
        if (isset($_POST['submit'])) {
            $_SESSION['answers'][] = $_POST['answerOneSub'];
            echo "<br>" . $_SESSION['answerOneSub'];
        }
    ?>