用回车事件写一个简易的留言板
时间: 2024-05-22 21:15:09 浏览: 37
我可以帮您回答这个问题。您可以使用PHP和MySQL来创建一个简单的留言板。以下是基本步骤:
1. 创建一个表格,包括字段:姓名、电子邮件、留言内容、时间
2. 在HTML表单中放置输入字段,其中包括一个或多个文本字段和一个提交按钮
3. 在PHP代码中处理表单提交并将数据插入数据库表中
4. 在网页上显示数据库中的留言内容
下面是一个基本的示例代码(仅供参考):
HTML代码:
<!DOCTYPE html>
<html>
<head>
<title>留言板</title>
</head>
<body>
<h1>留言板</h1>
<form action="form_process.php" method="post">
<label for="name">姓名:</label>
<input type="text" id="name" name="name"><br>
<label for="email">电子邮件:</label>
<input type="email" id="email" name="email"><br>
<label for="message">留言:</label>
<textarea id="message" name="message"></textarea><br>
<input type="submit" value="提交">
</form>
</body>
</html>
PHP代码(form_process.php文件):
<?php
//连接到数据库
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "test_db";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("连接失败:" . $conn->connect_error);
}
//处理表单提交
$name = $_POST["name"];
$email = $_POST["email"];
$message = $_POST["message"];
$time = date("Y-m-d H:i:s");
$sql = "INSERT INTO messages (name, email, message, time)
VALUES ('".$name."', '".$email."', '".$message."', '".$time."')";
if ($conn->query($sql) === TRUE) {
echo "留言成功";
} else {
echo "留言失败:" . $conn->error;
}
$conn->close();
?>
PHP代码(显示留言的页面messages.php):
<!DOCTYPE html>
<html>
<head>
<title>留言板信息</title>
</head>
<body>
<h1>留言板信息</h1>
<table>
<tr>
<th>姓名</th>
<th>电子邮件</th>
<th>留言内容</th>
<th>时间</th>
</tr>
<?php
//连接到数据库
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "test_db";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("连接失败:" . $conn->connect_error);
}
//从数据库中读取留言,按时间降序排序
$sql = "SELECT name, email, message, time FROM messages ORDER BY time DESC";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// 输出每行数据
while($row = $result->fetch_assoc()) {
echo "<tr><td>" . $row["name"]. "</td><td>" . $row["email"]. "</td><td>" . $row["message"]. "</td><td>" . $row["time"]. "</td></tr>";
}
} else {
echo "暂无留言";
}
$conn->close();
?>
</table>
</body>
</html>