
本教程详细阐述如何使用php和mysql高效且安全地处理多对多数据库关系,以学生选课系统为例。内容涵盖通过从数据库动态生成html复选框来准确捕获用户选择的多个课程id,以及如何利用mysql的`last_insert_id()`获取新插入的学生id,并将其与选定的课程id一并安全地插入到中间关联表。文章强调并示范了使用php `mysqli`预处理语句来有效防范sql注入攻击,确保数据交互的完整性和安全性。
在现代Web应用开发中,处理数据库中的多对多关系是一个常见需求。例如,在一个学生管理系统中,一个学生可以注册多门课程,同时一门课程也可以有多个学生注册。这种典型的多对多关系不能直接通过两张表实现,而是需要引入一张中间表(或称连接表、枢纽表)来维护它们之间的关联。本文将以学生选课系统为例,详细讲解如何通过PHP和MySQL实现这一功能,包括前端复选框的动态生成、后端数据的安全处理,并重点强调使用预处理语句来防范SQL注入。
数据库设计基础
为了有效地管理学生与课程之间的多对多关系,我们需要三张表:
-
tbl_students (学生表):存储学生的基本信息。
+---------+-----------+---------------+---------+ | st_id | st_name | st_email | st_code | +---------+-----------+---------------+---------+ | 1 | John Doe | john@example.com | 55555 | +---------+-----------+---------------+---------+
登录后复制 -
tbl_courses (课程表):存储课程的基本信息。
立即学习“PHP免费学习笔记(深入)”;
+---------+-----------+--------------------------+ | cr_id | cr_name | cr_desc | +---------+-----------+--------------------------+ | 1 | Guitar | Guitar course description| +---------+-----------+--------------------------+ | 2 | Bass | Bass course description | +---------+-----------+--------------------------+
登录后复制- cr_id: 主键,自动递增,唯一标识一门课程。
- cr_name: 课程名称。
- cr_desc: 课程描述。
-
tbl_students_courses (学生-课程关联表):中间表,用于存储学生和课程之间的关联关系。
+---------+---------+-----------+ | st_id | cr_id | date_insc | +---------+---------+-----------+ | 1 | 1 | 2023-01-01| | 1 | 5 | 2023-01-01| +---------+---------+-----------+
登录后复制- st_id: 外键,关联 tbl_students 表的 st_id。
- cr_id: 外键,关联 tbl_courses 表的 cr_id。
- date_insc: 记录学生注册课程的日期。
- 通常,(st_id, cr_id) 组合作为联合主键,确保一个学生不能重复注册同一门课程。
前端交互优化:动态生成课程选择复选框
在用户界面中,我们通常会提供一系列复选框供学生选择课程。关键在于,这些复选框的value属性应该存储课程的唯一标识ID,而不是课程名称。这样,当表单提交时,后端才能准确地获取到所选课程的ID。手动编写HTML并指定ID是不切实际的,尤其当课程列表经常变动时。最佳实践是从数据库中动态加载课程信息并生成复选框。

ECTouch是上海商创网络科技有限公司推出的一套基于 PHP 和 MySQL 数据库构建的开源且易于使用的移动商城网店系统!应用于各种服务器平台的高效、快速和易于管理的网店解决方案,采用稳定的MVC框架开发,完美对接ecshop系统与模板堂众多模板,为中小企业提供最佳的移动电商解决方案。ECTouch程序源代码完全无加密。安装时只需将已集成的文件夹放进指定位置,通过浏览器访问一键安装,无需对已有

0
获取课程数据函数
首先,我们需要一个PHP函数来从 tbl_courses 表中获取所有可用的课程。
<?php
/**
* 从数据库获取所有课程信息。
*
* @param mysqli $link 数据库连接对象。
* @return array 包含所有课程数据的数组。
*/
function getAllCourses(mysqli $link): array
{
$sql = "SELECT cr_id, cr_name, cr_desc FROM tbl_courses ORDER BY cr_name ASC";
$result = mysqli_query($link, $sql);
$courses = [];
if ($result) {
while ($row = mysqli_fetch_assoc($result)) {
$courses[] = $row;
}
mysqli_free_result($result); // 释放结果集
} else {
// 实际应用中应有更完善的错误处理
error_log("Error fetching courses: " . mysqli_error($link));
}
return $courses;
}
// 假设 $link 变量已通过 connection_db() 函数建立数据库连接
// 例如: $link = connection_db();
// 在实际应用中,应确保 $link 在此之前已被正确初始化。
?>
HTML/PHP动态生成复选框
在HTML表单中,使用PHP循环遍历 getAllCourses 函数返回的课程数据,动态生成复选框。
<div class="form-group">
<label class="col-form-label">选择课程</label>
<div class="form-check">
<?php
// 假设 $link 已经是一个有效的数据库连接对象
// 并且 getAllCourses 函数已被定义和包含
$courses = getAllCourses($link); // 调用函数获取课程列表
if (!empty($courses)) {
foreach ($courses as $course): ?>
<div class="form-check form-check-inline">
<!-- value 属性设置为课程ID,name 属性使用数组形式 course[] -->
<input class="form-check-input" name="course[]" type="checkbox" value="<?= htmlspecialchars($course['cr_id']) ?>">
<label class="form-check-label"><?= htmlspecialchars($course['cr_name']) ?></label>
</div>
<?php endforeach;
} else {
echo "<p>当前没有可用课程。</p>";
}
?>
</div>
</div>
关键点:
- name=”course[]”:这将使得PHP在表单提交后将所有选中的复选框值收集到一个名为 course 的数组中。
- value=”= htmlspecialchars($course[‘cr_id’]) ?>”:确保复选框的值是课程的ID,并使用 htmlspecialchars 防止潜在的XSS攻击。
后端数据处理:安全地插入学生与课程关联
当用户提交表单后,PHP后端需要执行以下步骤:
- 获取表单提交的学生信息和选中的课程ID数组。
- 将学生信息插入到 tbl_students 表。
- 获取新插入学生的 st_id。
- 遍历选中的课程ID,为每个课程ID和新学生ID,插入一条记录到 tbl_students_courses 表。
在此过程中,数据的安全性至关重要,必须使用预处理语句(Prepared Statements)来防止SQL注入攻击。
PHP后端处理逻辑
<?php
// 确保数据库连接 $link 已经建立,例如通过 include_once '../includes/functions.php'; 和 $link = connection_db();
// 假设 connection_db() 函数返回一个 mysqli 连接对象。
if (isset($_POST['submit'])) {
$studentName = trim($_POST['sname']);
$studentEmail = trim($_POST['semail']);
$studentCode = intval($_POST['scode']); // 学生代码通常是整数
// 获取选中的课程ID数组,如果未选择任何课程,则为空数组
$selectedCourses = $_POST['course'] ?? [];
// --- 步骤 1: 插入学生数据到 tbl_students (使用预处理语句) ---
// st_id 是自增主键,不需要在 INSERT 语句中指定
$queryStudent = "INSERT INTO tbl_students (st_name, st_email, st_code) VALUES (?, ?, ?)";
$stmtStudent = mysqli_prepare($link, $queryStudent);
if ($stmtStudent) {
// 绑定参数:s-string, s-string, i-integer
mysqli_stmt_bind_param($stmtStudent, "ssi", $studentName, $studentEmail, $studentCode);
if (mysqli_stmt_execute($stmtStudent)) {
// --- 步骤 2: 获取新插入学生的ID ---
// mysqli_insert_id() 返回上一次 INSERT 操作生成的 ID
$newStudentId = mysqli_insert_id($link);
// --- 步骤 3 & 4: 遍历选中的课程ID,插入到 tbl_students_courses (使用预处理语句) ---
if ($newStudentId && !empty($selectedCourses)) {
$queryStudentCourse = "INSERT INTO tbl_students_courses (st_id, cr_id, date_insc) VALUES (?, ?, ?)";
$stmtStudentCourse = mysqli_prepare($link, $queryStudentCourse);
if ($stmtStudentCourse) {
$currentDate = date('Y-m-d H:i:s'); // 获取当前时间作为注册日期
foreach ($selectedCourses as $courseId) {
// 确保 courseId 是整数,防止潜在的类型不匹配或注入
$courseId = intval($courseId);
// 绑定参数:i-integer (student ID), i-integer (course ID), s-string (date)
mysqli_stmt_bind_param($stmtStudentCourse, "iis", $newStudentId, $courseId, $currentDate);
mysqli_stmt_execute($stmtStudentCourse);
// 可以在这里添加错误检查:if (!mysqli_stmt_execute($stmtStudentCourse)) { ... }
}
mysqli_stmt_close($stmtStudentCourse); // 关闭课程关联的预处理语句
echo "<script>alert('学生及课程数据保存成功!');</script>";
// print "<script>top.location = 'index.php?id=2';</script>"; // 重定向
} else {
echo "<script>alert('错误:无法准备课程关联插入语句!" . mysqli_error($link) . "');</script>";
}
} else {
echo "<script>alert('学生数据保存成功,但未选择课程或获取学生ID失败!');</script>";
}
} else {
echo "<script>alert('错误:学生数据保存失败!" . mysqli_stmt_error($stmtStudent) . "');</script>";
}
以上就是PHP与MySQL多对多关系管理:动态复选框与安全数据插入实践的详细内容,更多请关注php中文网其它相关文章!
