php 实现留言
实现留言功能的基本步骤
使用PHP实现留言功能通常需要结合MySQL数据库存储数据,并通过HTML表单提交留言内容。以下是实现的核心代码和逻辑。
创建数据库表
在MySQL中创建存储留言的表,包含字段如ID、用户名、留言内容、时间等:
CREATE TABLE messages (
id INT AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(50) NOT NULL,
content TEXT NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
连接数据库
创建PHP文件(如config.php)存放数据库连接信息:
<?php
$host = 'localhost';
$dbname = 'your_database';
$username = 'your_username';
$password = 'your_password';
try {
$pdo = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
die("Connection failed: " . $e->getMessage());
}
?>
提交留言表单
创建HTML表单(如form.html)供用户提交留言:
<form action="submit_message.php" method="post">
<input type="text" name="username" placeholder="Your name" required>
<textarea name="content" placeholder="Your message" required></textarea>
<button type="submit">Submit</button>
</form>
处理表单提交
创建PHP文件(如submit_message.php)处理表单数据并存入数据库:
<?php
require 'config.php';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$username = htmlspecialchars($_POST['username']);
$content = htmlspecialchars($_POST['content']);
$stmt = $pdo->prepare("INSERT INTO messages (username, content) VALUES (?, ?)");
$stmt->execute([$username, $content]);
header("Location: view_messages.php");
exit;
}
?>
显示留言列表
创建PHP文件(如view_messages.php)从数据库读取并显示留言:
<?php
require 'config.php';
$stmt = $pdo->query("SELECT * FROM messages ORDER BY created_at DESC");
$messages = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>
<!DOCTYPE html>
<html>
<head>
<title>Messages</title>
</head>
<body>
<h1>Messages</h1>
<?php foreach ($messages as $message): ?>
<div>
<strong><?= htmlspecialchars($message['username']) ?></strong>
<p><?= htmlspecialchars($message['content']) ?></p>
<small><?= $message['created_at'] ?></small>
</div>
<?php endforeach; ?>
</body>
</html>
安全注意事项
对所有用户输入使用htmlspecialchars()函数防止XSS攻击。使用预处理语句防止SQL注入。在正式环境中应增加验证码、登录验证等功能增强安全性。







