使用php pdo实现emp_edit
时间: 2023-12-29 17:06:22 浏览: 79
好的,下面是一个简单的 emp_edit.php 页面实现,用于编辑员工信息:
```php
<?php
// 数据库连接参数
$host = "localhost";
$username = "root";
$password = "123456";
$dbname = "itcast";
// 连接数据库
$db = new PDO("mysql:host={$host};dbname={$dbname}", $username, $password);
// 处理编辑请求
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$id = $_POST['id'];
$name = $_POST['name'];
$gender = $_POST['gender'];
$hire_date = $_POST['hire_date'];
$address = $_POST['address'];
$phone = $_POST['phone'];
// 更新员工信息
$sql = "UPDATE employees SET name=:name, gender=:gender, hire_date=:hire_date, address=:address, phone=:phone WHERE id=:id";
$stmt = $db->prepare($sql);
$stmt->bindParam(':id', $id);
$stmt->bindParam(':name', $name);
$stmt->bindParam(':gender', $gender);
$stmt->bindParam(':hire_date', $hire_date);
$stmt->bindParam(':address', $address);
$stmt->bindParam(':phone', $phone);
$stmt->execute();
// 跳转回员工列表页面
header('Location: employees.php');
exit();
}
// 获取员工信息
$id = $_GET['id'];
$sql = "SELECT * FROM employees WHERE id=:id";
$stmt = $db->prepare($sql);
$stmt->bindParam(':id', $id);
$stmt->execute();
$employee = $stmt->fetch(PDO::FETCH_ASSOC);
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>编辑员工信息</title>
</head>
<body>
<h1>编辑员工信息</h1>
<form method="post">
<input type="hidden" name="id" value="<?php echo $employee['id']; ?>">
<p>
<label for="name">姓名:</label>
<input type="text" id="name" name="name" value="<?php echo $employee['name']; ?>">
</p>
<p>
<label for="gender">性别:</label>
<input type="radio" id="male" name="gender" value="男"<?php if ($employee['gender'] == '男') echo ' checked'; ?>>
<label for="male">男</label>
<input type="radio" id="female" name="gender" value="女"<?php if ($employee['gender'] == '女') echo ' checked'; ?>>
<label for="female">女</label>
</p>
<p>
<label for="hire_date">入职日期:</label>
<input type="date" id="hire_date" name="hire_date" value="<?php echo $employee['hire_date']; ?>">
</p>
<p>
<label for="address">地址:</label>
<input type="text" id="address" name="address" value="<?php echo $employee['address']; ?>">
</p>
<p>
<label for="phone">电话:</label>
<input type="text" id="phone" name="phone" value="<?php echo $employee['phone']; ?>">
</p>
<p>
<button type="submit">保存</button>
<button type="button" onclick="location.href='employees.php'">取消</button>
</p>
</form>
</body>
</html>
```
这里我们首先判断请求的方法是否为 POST,如果是 POST,则获取提交的员工信息,并更新数据库中对应的记录,然后跳转回员工列表页面。如果不是 POST,则根据传递过来的员工 id,获取员工信息并显示在表单中。在表单中,我们使用了 input type="hidden" 来隐藏员工的 id,方便后续进行更新操作。
阅读全文