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

学生登录后如何显示全部选修科目?现有代码仅展示一门科目

Problem Analysis

The original code only shows one subject because mysqli_fetch_array() only grabs the first row from your query result. The two hardcoded <h2> tags just repeat that single row's value instead of iterating through all the enrolled subjects the student has.

Solution Code

Here's the fixed code that will display both of the student's enrolled subjects:

<?php
session_start();
include_once("config.php");

// Redirect to login if user isn't authenticated
if(!isset($_SESSION['sid'])){
    header("Location:index.php");
    exit; // Stop code execution after redirect to avoid unexpected behavior
}

$studentId = $_SESSION['sid'];

// Use prepared statements to avoid SQL injection risks
$stmt = mysqli_prepare($mysqli, "SELECT en.*, su.descc FROM enrollment en INNER JOIN subject su ON su.year = en.year WHERE id = ?");
mysqli_stmt_bind_param($stmt, "s", $studentId);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
?>
<html>
<body>
    <h1>Your Enrolled Subjects</h1>
    <?php if(mysqli_num_rows($result) > 0): ?>
        <?php while($row = mysqli_fetch_array($result)): ?>
            <h2>Subject: <?php echo htmlspecialchars($row['descc']); ?></h2>
        <?php endwhile; ?>
    <?php else: ?>
        <p>No subjects found in your enrollment record.</p>
    <?php endif; ?>
</body>
</html>
Key Changes Explained
  • Loop Through All Rows: Replaced the single mysqli_fetch_array() call with a while loop. This goes through every row returned by your query, so all enrolled subjects get displayed.
  • Secure Query Handling: Switched to prepared statements instead of directly inserting the session ID into the query. This protects against SQL injection attacks, which is critical for user-facing code.
  • XSS Protection: Used htmlspecialchars() when echoing the subject name to prevent cross-site scripting attacks (stopping malicious code from being injected into the page).
  • Better Redirect Logic: Added exit after the header redirect to ensure no extra code runs if the user isn't logged in.
  • Empty Result Fallback: Added a check for zero rows to show a friendly message if the student has no enrolled subjects.
Quick Check

Make sure your enrollment and subject tables are correctly linked via the year column. If the join condition is wrong (for example, if you should be joining on a subject ID instead of year), the query won't return all the rows you expect. Double-check your database schema to confirm the relationship between these tables.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.11 08:26:47