php评论功能怎么实现
数据库设计
创建一个评论表存储评论数据,表结构可包含字段如id(主键)、content(评论内容)、user_id(用户ID)、created_at(发布时间)等。MySQL示例:
CREATE TABLE comments (
id INT AUTO_INCREMENT PRIMARY KEY,
content TEXT NOT NULL,
user_id INT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (user_id) REFERENCES users(id)
);
前端表单
在HTML中嵌入评论提交表单,需包含内容输入框和提交按钮:

<form action="submit_comment.php" method="post">
<textarea name="content" required></textarea>
<button type="submit">提交评论</button>
</form>
后端处理
创建PHP脚本接收表单数据并存入数据库,注意过滤用户输入防止SQL注入:
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$content = htmlspecialchars($_POST['content']);
$user_id = $_SESSION['user_id'] ?? 0; // 假设用户已登录
$pdo = new PDO('mysql:host=localhost;dbname=test', 'username', 'password');
$stmt = $pdo->prepare("INSERT INTO comments (content, user_id) VALUES (?, ?)");
$stmt->execute([$content, $user_id]);
header('Location: comments.php'); // 返回评论页
}
?>
评论展示
从数据库查询评论并显示在页面上:

<?php
$pdo = new PDO('mysql:host=localhost;dbname=test', 'username', 'password');
$comments = $pdo->query("SELECT * FROM comments ORDER BY created_at DESC")->fetchAll();
foreach ($comments as $comment) {
echo '<div class="comment">';
echo '<p>' . htmlspecialchars($comment['content']) . '</p>';
echo '<small>发布于 ' . $comment['created_at'] . '</small>';
echo '</div>';
}
?>
安全增强
添加CSRF防护令牌到表单中:
<input type="hidden" name="csrf_token" value="<?php echo $_SESSION['csrf_token']; ?>">
后端验证:
if ($_POST['csrf_token'] !== $_SESSION['csrf_token']) {
die('非法请求');
}






