You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

CodeIgniter项目中session数据question_number无法递增传递求助

Fixing the question_number Session Increment Issue in CodeIgniter

Let's break down why your question_number is stuck at 1 and how to fix it:

Core Problem

The main issue is that every time you submit the form, your code re-runs the "first time load" initialization logic, which resets question_number back to 1. This happens because you're not properly persisting the test_session_id across form submissions—when the page reloads after a POST, $test_session_id isn't retrieved from the GET/POST parameters, so the code thinks it's a fresh load and reinitializes everything.

Step-by-Step Fixes

1. Persist test_session_id Across Requests

First, make sure you're pulling the test_session_id from the request (either GET or POST) instead of generating a new one every time. Add this right after you fetch the test_id from GET:

$test_session_id = isset($_GET['test_session']) ? addslashes($_GET['test_session']) : 
                   (isset($_POST['session_id']) ? addslashes($_POST['session_id']) : generateTestSessionId());

2. Fix the Initialization Trigger

Instead of checking if $test_session_id exists, check if the question_number session variable is already set. This prevents reinitializing the session data on every form submit:

// Replace the old "FIRST TIME RUN" check with this
if (!isset($_SESSION['question_number'])) {
    // Your existing initialization code here (setting question_number to 1, score to 0, etc.)
}

3. Ensure Session Updates Stick

In your POST["LaunchTest"] block, make sure you're updating the session variables correctly and that the updated values are passed to the form. Also, add exit() after redirecting to the score page to stop further code execution:

if (isset($_POST["LaunchTest"])) {
    // ... existing code to fetch POST data ...
    
    // Update score in session when answer is correct
    if ($user_choice == $answer) {
        $score++;
        $_SESSION["score"] = $score;
    }
    
    // Increment and update question_number in session
    $question_number++;
    $_SESSION['question_number'] = $question_number;
    
    // ... existing DB update code ...
    
    if ($question_number > $_SESSION['total_questions']) {
        $score_output = calculateScore($score, $_SESSION['total_questions']);
        header("location:" . base_url() . "score?id=" . $test_id . "&test_session=" . $session_id."&score=". $score_output);
        exit(); // Critical: stops code from running after redirect
    } else {
        // Fetch next question and update the variables used in the form
        $myRandomNum = generateRandomNumber($start_id, $end_id);
        $quesionAtRand_str = getQuestionAtRandom($myRandomNum, $con);
        $QuestData_arr = explode("~", $quesionAtRand_str);
        
        $Question = $QuestData_arr[1];
        $OptA = $QuestData_arr[2];
        $OptB = $QuestData_arr[3];
        $OptC = $QuestData_arr[4];
        $OptD = $QuestData_arr[5];
        $Answer = $QuestData_arr[6];
    }
}

4. Use CodeIgniter's Session Class (Best Practice)

Instead of directly manipulating $_SESSION, use CodeIgniter's built-in session methods for better compatibility and security:

// Set session data
$this->session->set_userdata('question_number', $question_number);
$this->session->set_userdata('score', $score);

// Get session data
$question_number = $this->session->userdata('question_number');
$score = $this->session->userdata('score');

5. Fix SQL Injection Risk

Your current use of addslashes isn't sufficient to prevent SQL injection. Switch to prepared statements for your database queries:

// Replace your UPDATE query with this
$stmt = $con->prepare("UPDATE cbt_attempts_tbl SET currentQuestion = ?, score = ?, created_date = ? WHERE session_id = ?");
$stmt->bind_param("iiss", $current_question, $score, $today, $session_id);
$stmt->execute();
$stmt->close();

Why This Works

By persisting test_session_id and checking for existing session data instead of relying on variable existence, you ensure that the initialization logic only runs once—when the test first starts. After each form submit, the code will use the updated session values instead of resetting them.

内容的提问来源于stack exchange,提问作者MIike Eps

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 17:57:35