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

PHP报错Undefined index: next_id,答题网站功能异常求助

解决"Undefined index: next_id"错误的方案

这个错误本质是你的PHP代码直接访问$_POST['next_id'],但这个参数并非在所有请求场景下都存在——比如第一次加载页面、请求参数缺失时,就会触发未定义索引的警告。下面是具体的修复和优化步骤:

1. 先检查POST参数再使用,避免未定义索引

在所有用到$_POST['next_id']的PHP文件(包括ajax.php和ajax_get_correct_answer.php)里,不要直接读取这个参数,先通过isset()判断是否存在,给它一个默认值:

// 替换所有直接用$_POST['next_id']的地方
$next_id = isset($_POST['next_id']) ? (int)$_POST['next_id'] : -1;

这样当参数没传的时候,$next_id会默认设为-1,彻底避免未定义索引的报错。

2. 修复你提供的ajax.php代码问题

我帮你把原代码里的问题都修正了,包括参数处理、语法错误和单选框逻辑:

<?php
// Start the session
session_start();
$con=mysqli_connect("localhost","root","","quiz");
// change here to your data
// Check connection
if (mysqli_connect_errno()) {
    echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

// 先安全获取next_id,给默认值
$next_id = isset($_POST['next_id']) ? (int)$_POST['next_id'] : -1;

// Check the number of all questions
$response=mysqli_query($con,"select * from questions");
$number_of_all_questions = mysqli_num_rows($response);

if($next_id == 0){
    // reset to default
    $_SESSION["correct_score"] = 0;
    $_SESSION["not_correct_score"] = 0;
}

if($number_of_all_questions <= $next_id){
    // Quiz finished, show results
    echo"<div>
    <h2>Results:</h2>
    <p>Correct answers: {$_SESSION['correct_score']}</p>
    <p>Wrong answers: {$_SESSION['not_correct_score']}</p>
    </div>";
}else{
    // 用预处理语句避免SQL注入风险
    $stmt = mysqli_prepare($con, "select * from questions WHERE id =(select min(id) from questions where id > ?)");
    mysqli_stmt_bind_param($stmt, "i", $next_id);
    mysqli_stmt_execute($stmt);
    $response = mysqli_stmt_get_result($stmt);
?>
<?php while($result=mysqli_fetch_array($response,MYSQLI_ASSOC)){ ?>
<div id="question_<?= $result['id'] ?>" class='question' data-next-question="<?= $next_id ?>">
<!--check the class for plurals if error occurs-->
<h2><?= $result['id'] . ". " . $result['question_name'] ?></h2> <!-- 修复了字符串拼接的语法错误 -->
<div class='align'>
<input type="radio" value="1" id='radio1' name='answers'> <!-- 所有单选框name统一,才能实现单选 -->
<label id='ans1' for='radio1'><?= $result['answer1'] ?></label>
<br/>
<input type="radio" value="2" id='radio2' name='answers'>
<label id='ans2' for='radio2'><?= $result['answer2'] ?></label>
<br/>
<input type="radio" value="3" id='radio3' name='answers'>
<label id='ans3' for='radio3'><?= $result['answer3'] ?></label>
<br/>
<input type="radio" value="4" id='radio4' name='answers'>
<label id='ans4' for='radio4'><?= $result['answer4'] ?></label>
</div>
<br/>
<?php /*<input type="button" data-next-question="<?= $next_id ?>" id='next' value='Next!' name='question' class='butt'/> */?>
</div>
<?php }?>
<?php }?>
<?php mysqli_close($con); ?>

3. 修复ajax_get_correct_answer.php的问题

在这个文件的第28行左右,同样先处理next_id参数:

// 在使用$_POST['next_id']之前添加
$question_id = isset($_POST['next_id']) ? (int)$_POST['next_id'] : 0;
// 之后把所有原来的$_POST['next_id']替换成$question_id

4. 额外的JS逻辑优化

原JS里的单选判断和异步请求逻辑有点冗余,我帮你简化了一下,同时避免了两次请求覆盖DOM的问题:

$(document).ready(function(){
    $('body').on('click','input[type="radio"]', function(){
        var curr_id = $('.question').data('nextQuestion');
        var selectedAnswer = $('input[name="answers"]:checked').val(); // 统一name后直接获取选中值
        // 先判断答案对错,再加载下一题
        getCorrectAnswer(curr_id, selectedAnswer, function(){
            getQuestion(parseInt(curr_id)+1);
        });
    });

    function getQuestion(next_id){
        console.log(next_id);
        $.post("ajax.php", {
            next_id: next_id
        }, function(data, status){
            $('#container_for_questions').html(data);
        });
    }

    function getCorrectAnswer(questionId, selectedAnswer, callback){
        $.post("ajax_get_correct_answer.php", {
            question_id: questionId,
            selected_answer: selectedAnswer
        }, function(data, status){
            // 这里可以加对错提示,比如弹出"回答正确/错误"
            // 执行回调加载下一题
            if(typeof callback === 'function'){
                callback();
            }
        });
    }

    getQuestion(-1);
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 09:28:37