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

PHP新手求助:用$_Session和$_GET从数据库提取导师分类数据

How to Fetch Mentor Data by Category Using $_SESSION and $_GET in PHP

Hey there! Let's walk through this step by step—your youth mentor portal sounds like a great project, and this is a totally solvable common hurdle for new PHP devs. Here's how to make it work safely and smoothly:

First: Ensure Sessions Are Active

Before you use any $_SESSION variables, you need to start the session on every page that interacts with them (including your mentor list page and login/registration flows). Add this at the very top of your PHP files, before any HTML or output:

<?php
session_start();
?>

When students are on the category list page, each category should link to your mentor list page with a $_GET parameter for the category. Using a numeric category ID is more reliable than names (avoids issues with spaces/special characters):

<!-- Example category list on student dashboard -->
<ul>
  <li><a href="mentor_list.php?category_id=1">Career Guidance</a></li>
  <li><a href="mentor_list.php?category_id=2">Academic Support</a></li>
  <li><a href="mentor_list.php?category_id=3">Tech Skills</a></li>
</ul>

Step 2: Validate Student Session & Sanitize Category Parameter

On your mentor_list.php page, first confirm the student is logged in via $_SESSION. Then grab the category ID from $_GET and sanitize it to prevent bad input:

<?php
session_start();

// Check if student is logged in (adjust to match your session variable)
if (!isset($_SESSION['student_id'])) {
    // Redirect to login if not authenticated
    header("Location: student_login.php");
    exit();
}

// Get and sanitize category ID from $_GET
$category_id = isset($_GET['category_id']) ? (int)$_GET['category_id'] : 0;

// Handle invalid category input
if ($category_id === 0) {
    echo "<p>Please select a valid mentor category.</p>";
    exit();
}
?>

Step 3: Fetch Matching Mentors from Database (Securely!)

Use the sanitized $category_id to query your database for mentors offering that category. Always use prepared statements to avoid SQL injection—this is critical for security. Here's an example with PDO (my go-to for PHP database work):

<?php
// Database connection (update values to match your DB)
$db_host = 'localhost';
$db_name = 'your_database';
$db_user = 'your_username';
$db_pass = 'your_password';

try {
    $pdo = new PDO("mysql:host=$db_host;dbname=$db_name;charset=utf8mb4", $db_user, $db_pass);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    // Prepare query to get active mentors in the selected category
    $stmt = $pdo->prepare("
        SELECT m.name, m.specialty, m.bio, c.category_name
        FROM mentors m
        JOIN mentor_categories mc ON m.id = mc.mentor_id
        JOIN categories c ON mc.category_id = c.id
        WHERE mc.category_id = :category_id
        AND m.is_active = 1
    ");

    // Bind the safe category ID parameter
    $stmt->bindParam(':category_id', $category_id, PDO::PARAM_INT);
    $stmt->execute();

    // Fetch all matching mentors
    $mentors = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch(PDOException $e) {
    echo "Error loading mentors: " . $e->getMessage();
    exit();
}
?>

Step 4: Display Mentors to the Student

Loop through the $mentors array to show results, and handle cases where no mentors are available:

<!DOCTYPE html>
<html>
<head>
    <title>Mentors in Selected Category</title>
</head>
<body>
    <h1>Mentors for <?php echo htmlspecialchars($mentors[0]['category_name'] ?? 'Unknown Category'); ?></h1>

    <?php if (empty($mentors)): ?>
        <p>No mentors are available in this category right now. Check back soon!</p>
    <?php else: ?>
        <div class="mentor-grid">
            <?php foreach ($mentors as $mentor): ?>
                <div class="mentor-card">
                    <h3><?php echo htmlspecialchars($mentor['name']); ?></h3>
                    <p><strong>Specialty:</strong> <?php echo htmlspecialchars($mentor['specialty']); ?></p>
                    <p><?php echo htmlspecialchars($mentor['bio']); ?></p>
                    <!-- Add links to view profile or contact mentor here -->
                </div>
            <?php endforeach; ?>
        </div>
    <?php endif; ?>
</body>
</html>

Quick Tips for Success

  • Sanitize Output: Use htmlspecialchars() when echoing database data to the page to prevent XSS attacks.
  • Session Setup: Make sure you set $_SESSION['student_id'] (or similar) when the student successfully logs in.
  • Fallback Logic: Your code should gracefully handle cases where a student manually enters an invalid category_id in the URL.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 07:38:05