html留言板代码数据库
时间: 2023-11-14 07:22:36 浏览: 82
以下是一个简单的 HTML 留言板代码,使用 PHP 脚本连接到 MySQL 数据库来存储和检索留言信息:
HTML 代码:
```html
<!DOCTYPE html>
<html>
<head>
<title>留言板</title>
</head>
<body>
<h1>留言板</h1>
<form action="add_message.php" method="post">
<label for="name">姓名:</label>
<input type="text" name="name" id="name"><br><br>
<label for="email">电子邮件:</label>
<input type="email" name="email" id="email"><br><br>
<label for="message">留言:</label><br>
<textarea name="message" id="message" cols="30" rows="10"></textarea><br><br>
<input type="submit" value="提交">
</form>
<hr>
<h2>留言列表</h2>
<?php
// 连接数据库
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database_name";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("连接失败: " . $conn->connect_error);
}
// 查询留言
$sql = "SELECT name, email, message FROM messages";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "<p><strong>" . $row["name"] . "</strong> <" . $row["email"] . ">:<br>" . $row["message"] . "</p>";
}
} else {
echo "<p>暂无留言。</p>";
}
$conn->close();
?>
</body>
</html>
```
PHP 脚本(add_message.php):
```php
<?php
// 连接数据库
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database_name";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("连接失败: " . $conn->connect_error);
}
// 插入留言
$name = $_POST["name"];
$email = $_POST["email"];
$message = $_POST["message"];
$sql = "INSERT INTO messages (name, email, message) VALUES ('$name', '$email', '$message')";
if ($conn->query($sql) === TRUE) {
echo "<p>留言已提交。</p>";
} else {
echo "<p>提交出错:" . $conn->error . "</p>";
}
$conn->close();
?>
```
请注意,此代码仅供参考,并需要根据您的实际需求进行修改和完善。同时,为了确保数据安全性,请务必对数据库连接信息和 SQL 查询语句进行适当的保护和过滤。
阅读全文