写一个php使用pdo,实现员工添加功能PHP脚本
时间: 2024-03-03 12:50:39 浏览: 139
下面是一个使用 PDO 实现员工添加功能的 PHP 脚本:
```php
<?php
// 连接数据库
$servername = "localhost";
$username = "your_username";
$password = "your_password";
$dbname = "your_database";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// 设置 PDO 错误模式为异常
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// 获取表单提交的数据
$name = $_POST["name"];
$age = $_POST["age"];
$gender = $_POST["gender"];
$email = $_POST["email"];
$phone = $_POST["phone"];
$address = $_POST["address"];
$department = $_POST["department"];
$salary = $_POST["salary"];
$hire_date = $_POST["hire_date"];
// 构造 SQL 语句
$sql = "INSERT INTO employees (name, age, gender, email, phone, address, department, salary, hire_date)
VALUES (:name, :age, :gender, :email, :phone, :address, :department, :salary, :hire_date)";
// 使用 PDO 预处理语句,避免 SQL 注入攻击
$stmt = $conn->prepare($sql);
$stmt->bindParam(':name', $name);
$stmt->bindParam(':age', $age);
$stmt->bindParam(':gender', $gender);
$stmt->bindParam(':email', $email);
$stmt->bindParam(':phone', $phone);
$stmt->bindParam(':address', $address);
$stmt->bindParam(':department', $department);
$stmt->bindParam(':salary', $salary);
$stmt->bindParam(':hire_date', $hire_date);
// 执行 SQL 语句并检查是否成功
$stmt->execute();
echo "员工添加成功!";
} catch(PDOException $e) {
echo "添加失败: " . $e->getMessage();
}
// 关闭数据库连接
$conn = null;
?>
```
上述 PHP 脚本使用 PDO 连接到 MySQL 数据库,并通过预处理语句的方式向 employees 表中插入新的员工记录。其中,$servername、$username、$password 和 $dbname 变量需要根据你的实际情况进行修改。
阅读全文