php+mysql教学管理系统增删改查代码
时间: 2023-07-08 19:39:03 浏览: 84
以下是一个简单的PHP + MySQL教学管理系统的增删改查代码示例:
连接到MySQL数据库:
```php
// 连接到MySQL数据库
$connection = mysqli_connect('localhost', 'username', 'password', 'database_name');
// 检查连接是否成功
if (!$connection) {
die('连接数据库失败:' . mysqli_connect_error());
}
```
插入新记录:
```php
// 获取表单提交数据
$name = $_POST['name'];
$gender = $_POST['gender'];
$age = $_POST['age'];
// 构建插入SQL语句
$sql = "INSERT INTO students (name, gender, age) VALUES ('$name', '$gender', $age)";
// 执行插入操作
if (mysqli_query($connection, $sql)) {
echo "新记录插入成功";
} else {
echo "插入记录失败:" . mysqli_error($connection);
}
```
查询记录:
```php
// 构建查询SQL语句
$sql = "SELECT * FROM students";
// 执行查询操作
$result = mysqli_query($connection, $sql);
// 处理结果集
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
echo "姓名:" . $row['name'] . ",性别:" . $row['gender'] . ",年龄:" . $row['age'] . "<br>";
}
} else {
echo "没有记录";
}
```
更新记录:
```php
// 获取表单提交数据
$id = $_POST['id'];
$name = $_POST['name'];
$gender = $_POST['gender'];
$age = $_POST['age'];
// 构建更新SQL语句
$sql = "UPDATE students SET name='$name', gender='$gender', age=$age WHERE id=$id";
// 执行更新操作
if (mysqli_query($connection, $sql)) {
echo "记录更新成功";
} else {
echo "更新记录失败:" . mysqli_error($connection);
}
```
删除记录:
```php
// 获取要删除的记录ID
$id = $_GET['id'];
// 构建删除SQL语句
$sql = "DELETE FROM students WHERE id=$id";
// 执行删除操作
if (mysqli_query($connection, $sql)) {
echo "记录删除成功";
} else {
echo "删除记录失败:" . mysqli_error($connection);
}
```
最后,别忘了关闭数据库连接:
```php
mysqli_close($connection);
```
阅读全文