使用html写一个学生同学录的网页
时间: 2023-08-02 11:06:14 浏览: 49
好的,以下是一个简单的学生同学录网页示例:
```html
<!DOCTYPE html>
<html>
<head>
<title>学生同学录</title>
<style>
body {
font-family: Arial, sans-serif;
}
h1 {
text-align: center;
}
form {
max-width: 600px;
margin: 0 auto;
display: flex;
flex-wrap: wrap;
justify-content: space-between;
}
input[type="text"] {
flex-basis: 48%;
padding: 10px;
margin-bottom: 20px;
border: 1px solid #ccc;
border-radius: 5px;
}
input[type="submit"] {
background-color: #4CAF50;
color: white;
padding: 10px;
border: none;
border-radius: 5px;
cursor: pointer;
flex-basis: 100%;
margin-top: 20px;
}
table {
max-width: 600px;
margin: 0 auto;
border-collapse: collapse;
}
th, td {
padding: 10px;
border: 1px solid #ccc;
text-align: center;
}
th {
background-color: #4CAF50;
color: white;
}
</style>
</head>
<body>
<h1>学生同学录</h1>
<form method="post">
<input type="text" name="name" placeholder="姓名">
<input type="text" name="age" placeholder="年龄">
<input type="text" name="gender" placeholder="性别">
<input type="text" name="major" placeholder="专业">
<input type="submit" value="添加同学">
</form>
<?php
// 连接到数据库
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
$conn = new mysqli($servername, $username, $password, $dbname);
// 检查连接是否成功
if ($conn->connect_error) {
die("连接失败: " . $conn->connect_error);
}
// 处理表单提交
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = $_POST["name"];
$age = $_POST["age"];
$gender = $_POST["gender"];
$major = $_POST["major"];
$sql = "INSERT INTO students (name, age, gender, major)
VALUES ('$name', '$age', '$gender', '$major')";
if ($conn->query($sql) === TRUE) {
echo "<p>添加成功!</p>";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
// 显示学生列表
$sql = "SELECT * FROM students";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo "<table><tr><th>姓名</th><th>年龄</th><th>性别</th><th>专业</th></tr>";
while($row = $result->fetch_assoc()) {
echo "<tr><td>" . $row["name"] . "</td><td>" . $row["age"] . "</td><td>" . $row["gender"] . "</td><td>" . $row["major"] . "</td></tr>";
}
echo "</table>";
} else {
echo "<p>暂无同学信息!</p>";
}
// 关闭连接
$conn->close();
?>
</body>
</html>
```
这个网页包括一个表单,可以让用户添加新的同学信息。同时,它也会从数据库中读取已有的同学信息,并以表格的形式展示出来。需要注意的是,这个示例代码中使用了 PHP 语言来处理表单提交和数据库操作,因此需要在服务器端运行才能正常工作。