用PHP代码实现学生选课管理系统
时间: 2024-03-09 12:45:00 浏览: 100
好的,我可以帮你编写一个简单的学生选课管理系统的PHP代码,包含以下功能:
1. 学生登录
2. 学生选课
3. 学生退课
4. 查看已选课程
代码如下:
```php
<?php
// 数据库连接信息
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "dbname";
// 创建连接
$conn = new mysqli($servername, $username, $password, $dbname);
// 检测连接
if ($conn->connect_error) {
die("连接失败: " . $conn->connect_error);
}
// 学生登录
if ($_POST['action'] == 'login') {
$username = $_POST['username'];
$password = $_POST['password'];
$sql = "SELECT * FROM students WHERE username = '$username' AND password = '$password'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// 登录成功,保存学生信息到session
$row = $result->fetch_assoc();
session_start();
$_SESSION['student_id'] = $row['id'];
$_SESSION['student_name'] = $row['name'];
echo "登录成功!";
} else {
echo "用户名或密码错误!";
}
}
// 学生选课
if ($_POST['action'] == 'select_course') {
$student_id = $_SESSION['student_id'];
$course_id = $_POST['course_id'];
$sql = "INSERT INTO student_courses (student_id, course_id) VALUES ('$student_id', '$course_id')";
if ($conn->query($sql) === TRUE) {
echo "选课成功!";
} else {
echo "选课失败:" . $conn->error;
}
}
// 学生退课
if ($_POST['action'] == 'drop_course') {
$student_id = $_SESSION['student_id'];
$course_id = $_POST['course_id'];
$sql = "DELETE FROM student_courses WHERE student_id = '$student_id' AND course_id = '$course_id'";
if ($conn->query($sql) === TRUE) {
echo "退课成功!";
} else {
echo "退课失败:" . $conn->error;
}
}
// 查看已选课程
if ($_POST['action'] == 'view_courses') {
$student_id = $_SESSION['student_id'];
$sql = "SELECT courses.name FROM student_courses LEFT JOIN courses ON student_courses.course_id = courses.id WHERE student_courses.student_id = '$student_id'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo "已选课程:<br>";
while($row = $result->fetch_assoc()) {
echo $row["name"] . "<br>";
}
} else {
echo "未选课程!";
}
}
$conn->close();
?>
```
以上代码实现了学生登录、选课、退课、查看已选课程四个功能。你需要在数据库中创建两个表,一个是学生表(students),包含学生的id、用户名、密码、姓名等信息;另一个是课程表(courses),包含课程的id、名称、教师等信息。此外,还需要一个关联表(student_courses),用于记录学生选课信息,包含学生id和课程id两个字段。
阅读全文