学生登录后如何显示全部选修科目?现有代码仅展示一门科目
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.
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>
- Loop Through All Rows: Replaced the single
mysqli_fetch_array()call with awhileloop. 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
exitafter 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.
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

