用PHP代码实现学生选课管理系统
时间: 2024-04-25 09:26:01 浏览: 83
好的,以下是一个简单的学生选课管理系统的PHP代码实现:
1. 创建数据库
在MySQL中创建一个名为`course_selection`的数据库,并创建以下两个表:
```
CREATE TABLE `students` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(50) NOT NULL,
`password` varchar(50) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `courses` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(50) NOT NULL,
`teacher` varchar(50) NOT NULL,
`capacity` int(11) NOT NULL,
`selected` int(11) NOT NULL DEFAULT '0',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
```
其中`students`表用于存储学生信息,包括学生ID、姓名和密码;`courses`表用于存储课程信息,包括课程ID、名称、教师、容量和已选人数。
2. 连接数据库
在PHP代码中连接MySQL数据库:
```
$conn = mysqli_connect("localhost", "username", "password", "course_selection");
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
```
将`username`和`password`替换为您的MySQL用户名和密码。
3. 登录系统
学生需要输入正确的用户名和密码才能登录系统:
```
session_start();
if (isset($_POST['username']) && isset($_POST['password'])) {
$username = $_POST['username'];
$password = $_POST['password'];
$sql = "SELECT id FROM students WHERE name='$username' and password='$password'";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) == 1) {
$_SESSION['username'] = $username;
header("Location: index.php");
} else {
$message = "用户名或密码错误,请重新登录。";
}
}
```
4. 显示课程列表
学生登录后可以查看可选课程列表:
```
$sql = "SELECT * FROM courses";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
echo "<tr>";
echo "<td>" . $row['name'] . "</td>";
echo "<td>" . $row['teacher'] . "</td>";
echo "<td>" . $row['capacity'] . "</td>";
echo "<td>" . $row['selected'] . "</td>";
echo "<td>";
echo "<form method='post' action='select_course.php'>";
echo "<input type='hidden' name='course_id' value='" . $row['id'] . "'>";
echo "<input type='submit' name='submit' value='选课'>";
echo "</form>";
echo "</td>";
echo "</tr>";
}
} else {
echo "无可选课程。";
}
```
5. 选课
学生可以通过选课页面选课:
```
if (isset($_POST['submit'])) {
$course_id = $_POST['course_id'];
$username = $_SESSION['username'];
$sql = "SELECT capacity, selected FROM courses WHERE id='$course_id'";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) == 1) {
$row = mysqli_fetch_assoc($result);
if ($row['capacity'] > $row['selected']) {
$sql = "INSERT INTO selections (course_id, student_name) VALUES ('$course_id', '$username')";
if (mysqli_query($conn, $sql)) {
$sql = "UPDATE courses SET selected=selected+1 WHERE id='$course_id'";
mysqli_query($conn, $sql);
$message = "选课成功。";
} else {
$message = "选课失败,请重试。";
}
} else {
$message = "选课失败,该课程已满员。";
}
} else {
$message = "选课失败,课程不存在。";
}
}
```
以上就是一个简单的学生选课管理系统的PHP代码实现。当然,这只是一个示例,您可以根据您的需求进行修改和扩展。
阅读全文