php实现评论
PHP 实现评论功能
要实现一个基础的评论功能,需要处理数据库交互、表单提交和显示逻辑。以下是实现步骤:
创建数据库表
创建一个名为 comments 的表,包含必要字段:
CREATE TABLE comments (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100) NOT NULL,
email VARCHAR(100) NOT NULL,
comment TEXT NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
数据库连接
创建 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());
}
?>
评论表单
创建评论提交表单 comment_form.php:

<form action="submit_comment.php" method="post">
<input type="text" name="name" placeholder="Your Name" required>
<input type="email" name="email" placeholder="Your Email" required>
<textarea name="comment" placeholder="Your Comment" required></textarea>
<button type="submit">Submit Comment</button>
</form>
处理表单提交
创建 submit_comment.php 处理表单提交:
<?php
require 'config.php';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$name = htmlspecialchars($_POST['name']);
$email = htmlspecialchars($_POST['email']);
$comment = htmlspecialchars($_POST['comment']);
$stmt = $pdo->prepare("INSERT INTO comments (name, email, comment) VALUES (?, ?, ?)");
$stmt->execute([$name, $email, $comment]);
header("Location: comments.php");
exit();
}
?>
显示评论
创建 comments.php 显示所有评论:
<?php
require 'config.php';
$stmt = $pdo->query("SELECT * FROM comments ORDER BY created_at DESC");
$comments = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>
<?php foreach ($comments as $comment): ?>
<div class="comment">
<h4><?php echo $comment['name']; ?></h4>
<p><?php echo $comment['comment']; ?></p>
<small><?php echo $comment['created_at']; ?></small>
</div>
<?php endforeach; ?>
安全增强
添加CSRF保护和输入验证:

// 在表单中添加CSRF令牌
session_start();
$token = bin2hex(random_bytes(32));
$_SESSION['token'] = $token;
?>
<input type="hidden" name="token" value="<?php echo $token; ?>">
// 在提交处理中验证
if ($_POST['token'] !== $_SESSION['token']) {
die('Invalid CSRF token');
}
分页功能
实现评论分页:
$perPage = 5;
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$offset = ($page - 1) * $perPage;
$total = $pdo->query("SELECT COUNT(*) FROM comments")->fetchColumn();
$totalPages = ceil($total / $perPage);
$stmt = $pdo->prepare("SELECT * FROM comments ORDER BY created_at DESC LIMIT ? OFFSET ?");
$stmt->bindValue(1, $perPage, PDO::PARAM_INT);
$stmt->bindValue(2, $offset, PDO::PARAM_INT);
$stmt->execute();
回复功能
扩展数据库表支持回复:
ALTER TABLE comments ADD COLUMN parent_id INT DEFAULT NULL;
处理回复逻辑:
// 在评论显示中添加回复按钮
<button onclick="showReplyForm(<?php echo $comment['id']; ?>)">Reply</button>
// 显示回复表单
function showReplyForm(parentId) {
document.getElementById('reply-form-' + parentId).style.display = 'block';
}
这个实现包含了评论系统的基本功能,可以根据需求进一步扩展。






