3、创建insert.php文件获取form.html中提交,并储存到数据库中员工姓名、年龄、部门、居住地、员工等级(初级、中级、高级等)
时间: 2023-10-20 20:12:51 浏览: 28
以下示例代码:
form.html
```html
<!DOCTYPE html>
<html>
<head>
<title>Insert Employee Data</title>
</head>
<body>
<form action="insert.php" method="post">
<label>Name:</label><input type="text" name="name"><br>
<label>Age:</label><input type="number" name="age"><br>
<label>Department:</label><input type="text" name="department"><br>
<label>Residence:</label><input type="text" name="residence"><br>
<label>Level:</label>
<select name="level">
<option value="Junior">Junior</option>
<option value="Intermediate">Intermediate</option>
<option value="Senior">Senior</option>
</select><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
```
insert.php
```php
<?php
// Connect to database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Get data from form
$name = $_POST["name"];
$age = $_POST["age"];
$department = $_POST["department"];
$residence = $_POST["residence"];
$level = $_POST["level"];
// Insert data into database
$sql = "INSERT INTO employees (name, age, department, residence, level) VALUES ('$name', '$age', '$department', '$residence', '$level')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
```
在此示例中,我们使用了MySQL数据库,将员工数据插入到名为“employees”的表中。您需要将示例代码中的数据库连接参数替换为您自己的数据库连接参数。此外,为了防止SQL注入攻击,建议使用预处理语句来插入数据。