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

VS2015/C#中数据库查询后实现考试状态判断的if else语句编写求助

实现考试完成状态判断与页面跳转逻辑

看起来你正在收尾项目里的考试成绩查看功能,这个逻辑其实很清晰,我来帮你梳理一下具体的实现步骤,从SQL查询到后端分支处理再到前端提示,一步到位:

第一步:编写安全的SQL查询语句

首先你需要从数据库中获取当前学生对应考试的完成状态。假设你的表结构是student_exams,包含student_id(学生ID)、exam_id(考试ID)、is_completed(完成状态,1表示已完成,0表示未完成)这几个核心字段,那SQL可以这么写:

SELECT is_completed, exam_id 
FROM student_exams 
WHERE student_id = ? AND exam_id = ?;

⚠️ 重点:一定要用参数化查询(上面的?是占位符),不要直接拼接变量,避免SQL注入攻击。

第二步:后端的if-else分支处理

接下来根据查询结果做逻辑判断,这里我给你两个常用后端语言的示例:

PHP(PDO示例)

// 假设你已经通过PDO完成了数据库连接和参数绑定,执行了查询
$stmt->execute([$studentId, $examId]);
$examRecord = $stmt->fetch(PDO::FETCH_ASSOC);

if ($examRecord && $examRecord['is_completed'] === 1) {
    // 考试已完成:重定向到成绩结果页,带上考试ID参数
    header("Location: exam_result.php?exam_id=" . $examRecord['exam_id']);
    exit; // 重定向后必须终止后续代码执行,避免冗余输出
} else {
    // 考试未完成:设置提示信息,后续传递到前端页面
    $warningMsg = "你尚未完成该考试,暂时无法查看成绩哦!";
}

Python Flask示例

from flask import redirect, url_for, render_template, session

@app.route('/verify_exam/<int:exam_id>')
def verify_exam(exam_id):
    # 从会话中获取已登录学生的ID(确保已做身份验证)
    student_id = session.get('current_student_id')
    if not student_id:
        return redirect(url_for('login'))

    # 执行SQL查询
    cursor = db.connection.cursor(dictionary=True)
    cursor.execute(
        "SELECT is_completed FROM student_exams WHERE student_id = %s AND exam_id = %s",
        (student_id, exam_id)
    )
    exam_record = cursor.fetchone()

    if exam_record and exam_record['is_completed']:
        # 已完成:跳转到成绩页
        return redirect(url_for('show_exam_result', exam_id=exam_id))
    else:
        # 未完成:携带提示信息渲染原页面
        return render_template('exam_entry.html', warning_msg="你尚未完成该考试,无法查看成绩!")

第三步:前端显示提示信息

后端传递的提示信息,需要在页面顶部渲染出来,这里也给对应示例:

PHP前端模板

<!-- 页面顶部位置 -->
<?php if (isset($warningMsg)): ?>
    <div class="alert alert-warning" style="margin-bottom: 1rem;">
        <?php echo htmlspecialchars($warningMsg); ?>
    </div>
<?php endif; ?>

Flask Jinja2模板

<!-- 页面顶部位置 -->
{% if warning_msg %}
    <div class="alert alert-warning" style="margin-bottom: 1rem;">
        {{ warning_msg }}
    </div>
{% endif %}

额外注意事项

  • 身份验证:一定要确保student_id是从已验证的会话或请求中获取,不能让用户通过URL参数随意篡改,防止越权查看他人成绩。
  • XSS防护:前端输出提示信息时,要做HTML转义(PHP用htmlspecialchars,Jinja2默认自动转义),避免跨站脚本攻击。
  • 边界情况:要考虑查询不到记录的情况(比如学生从未参加过该考试),这种情况也应该归到“未完成”分支,给出对应的提示。

内容的提问来源于stack exchange,提问作者Adrian B.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 09:28:12