php如何实现留言
使用PHP实现留言功能
创建一个简单的留言功能需要处理表单提交、数据存储和显示。以下是实现的基本步骤:
创建数据库表
在MySQL中创建一个表来存储留言信息:
CREATE TABLE messages (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(50) NOT NULL,
email VARCHAR(100),
content TEXT NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
创建留言表单
HTML表单用于收集用户输入:

<form action="submit.php" method="post">
<label for="name">姓名:</label>
<input type="text" id="name" name="name" required>
<label for="email">邮箱:</label>
<input type="email" id="email" name="email">
<label for="content">留言内容:</label>
<textarea id="content" name="content" required></textarea>
<button type="submit">提交留言</button>
</form>
处理表单提交
创建submit.php处理表单数据并存入数据库:
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$name = htmlspecialchars($_POST['name']);
$email = htmlspecialchars($_POST['email']);
$content = htmlspecialchars($_POST['content']);
$conn = new mysqli('localhost', 'username', 'password', 'database');
if ($conn->connect_error) {
die("连接失败: " . $conn->connect_error);
}
$stmt = $conn->prepare("INSERT INTO messages (name, email, content) VALUES (?, ?, ?)");
$stmt->bind_param("sss", $name, $email, $content);
if ($stmt->execute()) {
header("Location: messages.php");
} else {
echo "留言提交失败";
}
$stmt->close();
$conn->close();
}
?>
显示留言列表
创建messages.php显示所有留言:

<?php
$conn = new mysqli('localhost', 'username', 'password', 'database');
if ($conn->connect_error) {
die("连接失败: " . $conn->connect_error);
}
$result = $conn->query("SELECT * FROM messages ORDER BY created_at DESC");
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
echo "<div class='message'>";
echo "<h3>" . htmlspecialchars($row['name']) . "</h3>";
if (!empty($row['email'])) {
echo "<p>邮箱:" . htmlspecialchars($row['email']) . "</p>";
}
echo "<p>" . htmlspecialchars($row['content']) . "</p>";
echo "<small>" . $row['created_at'] . "</small>";
echo "</div>";
}
} else {
echo "暂无留言";
}
$conn->close();
?>
安全注意事项
对用户输入进行验证和过滤,防止SQL注入和XSS攻击:
$name = filter_input(INPUT_POST, 'name', FILTER_SANITIZE_STRING);
$email = filter_input(INPUT_POST, 'email', FILTER_SANITIZE_EMAIL);
$content = filter_input(INPUT_POST, 'content', FILTER_SANITIZE_STRING);
使用预处理语句防止SQL注入,如上面示例中的prepare和bind_param方法。
扩展功能
可以添加分页功能显示留言:
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$limit = 10;
$offset = ($page - 1) * $limit;
$result = $conn->query("SELECT * FROM messages ORDER BY created_at DESC LIMIT $limit OFFSET $offset");
添加管理员回复功能,可以在数据库中添加reply字段,并创建管理员界面进行回复。






