php评论功能实现代码
实现PHP评论功能的基本代码
PHP评论功能通常涉及前端表单提交、后端数据处理和数据库存储。以下是一个基础的实现示例:
数据库表结构(MySQL)

CREATE TABLE comments (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100) NOT NULL,
email VARCHAR(100),
content TEXT NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
前端HTML表单
<form action="submit_comment.php" method="post">
<input type="text" name="name" placeholder="Your Name" required>
<input type="email" name="email" placeholder="Your Email">
<textarea name="content" placeholder="Your Comment" required></textarea>
<button type="submit">Submit Comment</button>
</form>
后端处理(submit_comment.php)
<?php
// 连接数据库
$db = new PDO('mysql:host=localhost;dbname=your_database', 'username', 'password');
// 获取表单数据
$name = $_POST['name'];
$email = $_POST['email'] ?? null;
$content = $_POST['content'];
// 防止SQL注入
$stmt = $db->prepare("INSERT INTO comments (name, email, content) VALUES (?, ?, ?)");
$stmt->execute([$name, $email, $content]);
// 重定向回评论页
header('Location: comments.php');
exit;
?>
显示评论(comments.php)
<?php
$db = new PDO('mysql:host=localhost;dbname=your_database', 'username', 'password');
$comments = $db->query("SELECT * FROM comments ORDER BY created_at DESC")->fetchAll(PDO::FETCH_ASSOC);
foreach ($comments as $comment) {
echo "<div class='comment'>";
echo "<h3>{$comment['name']}</h3>";
if ($comment['email']) {
echo "<p>Email: {$comment['email']}</p>";
}
echo "<p>{$comment['content']}</p>";
echo "<small>{$comment['created_at']}</small>";
echo "</div>";
}
?>
安全增强措施
数据验证和过滤
$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);
防止XSS攻击

echo htmlspecialchars($comment['content'], ENT_QUOTES, 'UTF-8');
扩展功能建议
分页显示评论
$page = $_GET['page'] ?? 1;
$limit = 10;
$offset = ($page - 1) * $limit;
$comments = $db->query("SELECT * FROM comments ORDER BY created_at DESC LIMIT $limit OFFSET $offset");
回复功能实现
ALTER TABLE comments ADD COLUMN parent_id INT DEFAULT NULL;
这个基础实现可以根据需要扩展更多功能,如用户认证、富文本编辑、表情支持等。






