Skip to content

12.8 实操:学生信息管理(增删改查)

本实操将创建一个完整的学生信息管理系统,包含学生信息的增加、删除、修改和查询功能。

功能需求

  1. 学生列表:显示所有学生信息
  2. 添加学生:添加新的学生信息
  3. 编辑学生:修改现有学生信息
  4. 删除学生:删除学生信息
  5. 搜索学生:根据姓名或学号搜索学生

数据库设计

创建学生表

sql
CREATE TABLE students (
    id INT AUTO_INCREMENT PRIMARY KEY,
    student_id VARCHAR(20) NOT NULL UNIQUE,
    name VARCHAR(50) NOT NULL,
    gender ENUM('男', '女') NOT NULL,
    age INT NOT NULL,
    class VARCHAR(50) NOT NULL,
    major VARCHAR(100) NOT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
);

实现代码

1. 配置文件

php
<?php
// config.php
define('DB_HOST', 'localhost');
define('DB_USER', 'root');
define('DB_PASS', '');
define('DB_NAME', 'test');
define('DB_CHARSET', 'utf8mb4');
?>

2. 数据库连接

php
<?php
// db.php
require_once 'config.php';

function getDbConnection() {
    $conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
    
    if ($conn->connect_error) {
        die('数据库连接失败: ' . $conn->connect_error);
    }
    
    $conn->set_charset(DB_CHARSET);
    return $conn;
}
?>

3. 学生列表页面

php
<?php
// index.php
require_once 'db.php';
$conn = getDbConnection();

// 搜索功能
$search = '';
if (isset($_GET['search'])) {
    $search = $_GET['search'];
    $stmt = $conn->prepare("SELECT * FROM students WHERE student_id LIKE ? OR name LIKE ? ORDER BY id DESC");
    $searchTerm = "%$search%";
    $stmt->bind_param("ss", $searchTerm, $searchTerm);
    $stmt->execute();
    $result = $stmt->get_result();
} else {
    // 显示所有学生
    $sql = "SELECT * FROM students ORDER BY id DESC";
    $result = $conn->query($sql);
}
?>

<!DOCTYPE html>
<html>
<head>
    <title>学生信息管理系统</title>
    <style>
        body { font-family: Arial, sans-serif; max-width: 1000px; margin: 0 auto; padding: 20px; }
        h1 { text-align: center; color: #333; }
        .search-form { margin: 20px 0; text-align: center; }
        .search-form input { padding: 10px; width: 300px; }
        .search-form button { padding: 10px 20px; background-color: #4CAF50; color: white; border: none; cursor: pointer; }
        table { width: 100%; border-collapse: collapse; margin: 20px 0; }
        th, td { padding: 10px; text-align: left; border-bottom: 1px solid #ddd; }
        th { background-color: #f2f2f2; font-weight: bold; }
        tr:hover { background-color: #f5f5f5; }
        .actions { display: flex; gap: 10px; }
        .btn { padding: 5px 10px; text-decoration: none; border-radius: 4px; color: white; }
        .btn-add { background-color: #4CAF50; }
        .btn-edit { background-color: #2196F3; }
        .btn-delete { background-color: #f44336; }
        .message { padding: 10px; margin: 10px 0; border-radius: 4px; }
        .success { background-color: #d4edda; color: #155724; border: 1px solid #c3e6cb; }
        .error { background-color: #f8d7da; color: #721c24; border: 1px solid #f5c6cb; }
    </style>
</head>
<body>
    <h1>学生信息管理系统</h1>
    
    <?php if (isset($_GET['success'])): ?>
        <div class="message success">
            <?php echo $_GET['success']; ?>
        </div>
    <?php endif; ?>
    
    <?php if (isset($_GET['error'])): ?>
        <div class="message error">
            <?php echo $_GET['error']; ?>
        </div>
    <?php endif; ?>
    
    <div class="search-form">
        <form action="" method="get">
            <input type="text" name="search" placeholder="搜索学号或姓名" value="<?php echo $search; ?>">
            <button type="submit">搜索</button>
            <a href="add.php" class="btn btn-add">添加学生</a>
        </form>
    </div>
    
    <table>
        <tr>
            <th>ID</th>
            <th>学号</th>
            <th>姓名</th>
            <th>性别</th>
            <th>年龄</th>
            <th>班级</th>
            <th>专业</th>
            <th>创建时间</th>
            <th>操作</th>
        </tr>
        <?php if ($result->num_rows > 0): ?>
            <?php while ($row = $result->fetch_assoc()): ?>
                <tr>
                    <td><?php echo $row['id']; ?></td>
                    <td><?php echo $row['student_id']; ?></td>
                    <td><?php echo $row['name']; ?></td>
                    <td><?php echo $row['gender']; ?></td>
                    <td><?php echo $row['age']; ?></td>
                    <td><?php echo $row['class']; ?></td>
                    <td><?php echo $row['major']; ?></td>
                    <td><?php echo $row['created_at']; ?></td>
                    <td class="actions">
                        <a href="edit.php?id=<?php echo $row['id']; ?>" class="btn btn-edit">编辑</a>
                        <a href="delete.php?id=<?php echo $row['id']; ?>" class="btn btn-delete" onclick="return confirm('确定要删除这个学生吗?');">删除</a>
                    </td>
                </tr>
            <?php endwhile; ?>
        <?php else: ?>
            <tr>
                <td colspan="9" style="text-align: center;">暂无学生信息</td>
            </tr>
        <?php endif; ?>
    </table>
</body>
</html>

<?php
$result->free();
$conn->close();
?>

4. 添加学生页面

php
<?php
// add.php
require_once 'db.php';
$conn = getDbConnection();

$errors = [];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // 表单验证
    if (empty($_POST['student_id'])) {
        $errors[] = '学号不能为空';
    }
    
    if (empty($_POST['name'])) {
        $errors[] = '姓名不能为空';
    }
    
    if (empty($_POST['gender'])) {
        $errors[] = '性别不能为空';
    }
    
    if (empty($_POST['age'])) {
        $errors[] = '年龄不能为空';
    } else if (!is_numeric($_POST['age'])) {
        $errors[] = '年龄必须是数字';
    }
    
    if (empty($_POST['class'])) {
        $errors[] = '班级不能为空';
    }
    
    if (empty($_POST['major'])) {
        $errors[] = '专业不能为空';
    }
    
    if (empty($errors)) {
        // 检查学号是否已存在
        $stmt = $conn->prepare("SELECT id FROM students WHERE student_id = ?");
        $stmt->bind_param("s", $_POST['student_id']);
        $stmt->execute();
        $result = $stmt->get_result();
        
        if ($result->num_rows > 0) {
            $errors[] = '学号已存在';
        } else {
            // 插入学生信息
            $stmt = $conn->prepare("INSERT INTO students (student_id, name, gender, age, class, major) VALUES (?, ?, ?, ?, ?, ?)");
            $stmt->bind_param("sssiss", $student_id, $name, $gender, $age, $class, $major);
            
            $student_id = htmlspecialchars($_POST['student_id']);
            $name = htmlspecialchars($_POST['name']);
            $gender = $_POST['gender'];
            $age = (int)$_POST['age'];
            $class = htmlspecialchars($_POST['class']);
            $major = htmlspecialchars($_POST['major']);
            
            if ($stmt->execute()) {
                header('Location: index.php?success=学生添加成功');
                exit;
            } else {
                $errors[] = '添加失败: ' . $stmt->error;
            }
        }
        
        $stmt->close();
    }
}

$conn->close();
?>

<!DOCTYPE html>
<html>
<head>
    <title>添加学生</title>
    <style>
        body { font-family: Arial, sans-serif; max-width: 500px; margin: 0 auto; padding: 20px; }
        h1 { text-align: center; color: #333; }
        .error { color: red; margin: 10px 0; }
        .form-group { margin: 15px 0; }
        label { display: block; margin-bottom: 5px; font-weight: bold; }
        input, select { width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 4px; box-sizing: border-box; }
        .btn { padding: 10px 20px; background-color: #4CAF50; color: white; border: none; border-radius: 4px; cursor: pointer; }
        .btn-back { background-color: #9e9e9e; margin-right: 10px; text-decoration: none; color: white; padding: 10px 20px; border-radius: 4px; }
        .form-actions { margin-top: 20px; }
    </style>
</head>
<body>
    <h1>添加学生</h1>
    
    <?php if (!empty($errors)): ?>
        <div class="error">
            <ul>
                <?php foreach ($errors as $error): ?>
                    <li><?php echo $error; ?></li>
                <?php endforeach; ?>
            </ul>
        </div>
    <?php endif; ?>
    
    <form action="" method="post">
        <div class="form-group">
            <label>学号: <input type="text" name="student_id" value="<?php echo isset($_POST['student_id']) ? htmlspecialchars($_POST['student_id']) : ''; ?>"></label>
        </div>
        <div class="form-group">
            <label>姓名: <input type="text" name="name" value="<?php echo isset($_POST['name']) ? htmlspecialchars($_POST['name']) : ''; ?>"></label>
        </div>
        <div class="form-group">
            <label>性别: 
                <select name="gender">
                    <option value="">请选择</option>
                    <option value="男" <?php echo isset($_POST['gender']) && $_POST['gender'] === '男' ? 'selected' : ''; ?>></option>
                    <option value="女" <?php echo isset($_POST['gender']) && $_POST['gender'] === '女' ? 'selected' : ''; ?>></option>
                </select>
            </label>
        </div>
        <div class="form-group">
            <label>年龄: <input type="text" name="age" value="<?php echo isset($_POST['age']) ? htmlspecialchars($_POST['age']) : ''; ?>"></label>
        </div>
        <div class="form-group">
            <label>班级: <input type="text" name="class" value="<?php echo isset($_POST['class']) ? htmlspecialchars($_POST['class']) : ''; ?>"></label>
        </div>
        <div class="form-group">
            <label>专业: <input type="text" name="major" value="<?php echo isset($_POST['major']) ? htmlspecialchars($_POST['major']) : ''; ?>"></label>
        </div>
        <div class="form-actions">
            <a href="index.php" class="btn-back">返回</a>
            <button type="submit" class="btn">添加</button>
        </div>
    </form>
</body>
</html>

5. 编辑学生页面

php
<?php
// edit.php
require_once 'db.php';
$conn = getDbConnection();

$errors = [];
$student = null;

if (isset($_GET['id'])) {
    $id = (int)$_GET['id'];
    
    // 获取学生信息
    $stmt = $conn->prepare("SELECT * FROM students WHERE id = ?");
    $stmt->bind_param("i", $id);
    $stmt->execute();
    $result = $stmt->get_result();
    
    if ($result->num_rows > 0) {
        $student = $result->fetch_assoc();
    } else {
        header('Location: index.php?error=学生不存在');
        exit;
    }
    
    $stmt->close();
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && $student) {
    // 表单验证
    if (empty($_POST['student_id'])) {
        $errors[] = '学号不能为空';
    }
    
    if (empty($_POST['name'])) {
        $errors[] = '姓名不能为空';
    }
    
    if (empty($_POST['gender'])) {
        $errors[] = '性别不能为空';
    }
    
    if (empty($_POST['age'])) {
        $errors[] = '年龄不能为空';
    } else if (!is_numeric($_POST['age'])) {
        $errors[] = '年龄必须是数字';
    }
    
    if (empty($_POST['class'])) {
        $errors[] = '班级不能为空';
    }
    
    if (empty($_POST['major'])) {
        $errors[] = '专业不能为空';
    }
    
    if (empty($errors)) {
        // 检查学号是否已存在(排除当前学生)
        $stmt = $conn->prepare("SELECT id FROM students WHERE student_id = ? AND id != ?");
        $stmt->bind_param("si", $_POST['student_id'], $id);
        $stmt->execute();
        $result = $stmt->get_result();
        
        if ($result->num_rows > 0) {
            $errors[] = '学号已存在';
        } else {
            // 更新学生信息
            $stmt = $conn->prepare("UPDATE students SET student_id = ?, name = ?, gender = ?, age = ?, class = ?, major = ? WHERE id = ?");
            $stmt->bind_param("sssissi", $student_id, $name, $gender, $age, $class, $major, $id);
            
            $student_id = htmlspecialchars($_POST['student_id']);
            $name = htmlspecialchars($_POST['name']);
            $gender = $_POST['gender'];
            $age = (int)$_POST['age'];
            $class = htmlspecialchars($_POST['class']);
            $major = htmlspecialchars($_POST['major']);
            
            if ($stmt->execute()) {
                header('Location: index.php?success=学生更新成功');
                exit;
            } else {
                $errors[] = '更新失败: ' . $stmt->error;
            }
        }
        
        $stmt->close();
    }
}

$conn->close();
?>

<!DOCTYPE html>
<html>
<head>
    <title>编辑学生</title>
    <style>
        body { font-family: Arial, sans-serif; max-width: 500px; margin: 0 auto; padding: 20px; }
        h1 { text-align: center; color: #333; }
        .error { color: red; margin: 10px 0; }
        .form-group { margin: 15px 0; }
        label { display: block; margin-bottom: 5px; font-weight: bold; }
        input, select { width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 4px; box-sizing: border-box; }
        .btn { padding: 10px 20px; background-color: #2196F3; color: white; border: none; border-radius: 4px; cursor: pointer; }
        .btn-back { background-color: #9e9e9e; margin-right: 10px; text-decoration: none; color: white; padding: 10px 20px; border-radius: 4px; }
        .form-actions { margin-top: 20px; }
    </style>
</head>
<body>
    <h1>编辑学生</h1>
    
    <?php if (!empty($errors)): ?>
        <div class="error">
            <ul>
                <?php foreach ($errors as $error): ?>
                    <li><?php echo $error; ?></li>
                <?php endforeach; ?>
            </ul>
        </div>
    <?php endif; ?>
    
    <?php if ($student): ?>
        <form action="" method="post">
            <div class="form-group">
                <label>学号: <input type="text" name="student_id" value="<?php echo isset($_POST['student_id']) ? htmlspecialchars($_POST['student_id']) : $student['student_id']; ?>"></label>
            </div>
            <div class="form-group">
                <label>姓名: <input type="text" name="name" value="<?php echo isset($_POST['name']) ? htmlspecialchars($_POST['name']) : $student['name']; ?>"></label>
            </div>
            <div class="form-group">
                <label>性别: 
                    <select name="gender">
                        <option value="">请选择</option>
                        <option value="男" <?php echo (isset($_POST['gender']) ? $_POST['gender'] : $student['gender']) === '男' ? 'selected' : ''; ?>></option>
                        <option value="女" <?php echo (isset($_POST['gender']) ? $_POST['gender'] : $student['gender']) === '女' ? 'selected' : ''; ?>></option>
                    </select>
                </label>
            </div>
            <div class="form-group">
                <label>年龄: <input type="text" name="age" value="<?php echo isset($_POST['age']) ? htmlspecialchars($_POST['age']) : $student['age']; ?>"></label>
            </div>
            <div class="form-group">
                <label>班级: <input type="text" name="class" value="<?php echo isset($_POST['class']) ? htmlspecialchars($_POST['class']) : $student['class']; ?>"></label>
            </div>
            <div class="form-group">
                <label>专业: <input type="text" name="major" value="<?php echo isset($_POST['major']) ? htmlspecialchars($_POST['major']) : $student['major']; ?>"></label>
            </div>
            <div class="form-actions">
                <a href="index.php" class="btn-back">返回</a>
                <button type="submit" class="btn">更新</button>
            </div>
        </form>
    <?php endif; ?>
</body>
</html>

6. 删除学生页面

php
<?php
// delete.php
require_once 'db.php';
$conn = getDbConnection();

if (isset($_GET['id'])) {
    $id = (int)$_GET['id'];
    
    // 删除学生
    $stmt = $conn->prepare("DELETE FROM students WHERE id = ?");
    $stmt->bind_param("i", $id);
    
    if ($stmt->execute()) {
        header('Location: index.php?success=学生删除成功');
    } else {
        header('Location: index.php?error=删除失败: ' . $stmt->error);
    }
    
    $stmt->close();
}

$conn->close();
?>

代码解析

  1. 配置文件:定义数据库连接参数
  2. 数据库连接:提供数据库连接功能
  3. 学生列表页面:显示所有学生信息,支持搜索功能
  4. 添加学生页面:添加新的学生信息,包含表单验证
  5. 编辑学生页面:修改现有学生信息,包含表单验证
  6. 删除学生页面:删除学生信息,包含确认提示

注意事项

  1. 安全性

    • 使用预处理语句防止 SQL 注入攻击
    • 验证用户输入,确保数据有效性
    • 转义输出,防止 XSS 攻击
  2. 用户体验

    • 提供清晰的错误提示
    • 操作成功后显示成功消息
    • 删除操作前添加确认提示
  3. 功能完整性

    • 实现完整的增删改查功能
    • 支持按学号和姓名搜索
    • 验证学号唯一性

练习

  1. 完善学生信息管理系统,添加更多字段,如联系方式、家庭住址等
  2. 实现学生信息的导入导出功能
  3. 添加用户登录系统,实现权限控制
  4. 优化界面设计,添加分页功能
  5. 实现学生信息的批量操作

© 2026 编程马·菜鸟教程 版权所有