php评论功能实现代码
基础PHP评论功能实现
数据库表结构设计(MySQL)
CREATE TABLE comments (
id INT AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(50) NOT NULL,
email VARCHAR(100),
content TEXT NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
post_id INT NOT NULL
);
评论提交表单
<form action="submit_comment.php" method="POST">
<input type="text" name="username" placeholder="Your Name" required>
<input type="email" name="email" placeholder="Your Email">
<textarea name="content" placeholder="Your Comment" required></textarea>
<input type="hidden" name="post_id" value="<?php echo $post_id; ?>">
<button type="submit">Submit Comment</button>
</form>
评论处理脚本(submit_comment.php)
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$username = htmlspecialchars($_POST['username']);
$email = filter_var($_POST['email'], FILTER_VALIDATE_EMAIL);
$content = htmlspecialchars($_POST['content']);
$post_id = (int)$_POST['post_id'];
if (!empty($username) && !empty($content)) {
$db = new PDO('mysql:host=localhost;dbname=your_database', 'username', 'password');
$stmt = $db->prepare("INSERT INTO comments (username, email, content, post_id) VALUES (?, ?, ?, ?)");
$stmt->execute([$username, $email, $content, $post_id]);
header("Location: post.php?id=$post_id");
exit();
}
}
?>
显示评论功能
<?php
$post_id = (int)$_GET['id'];
$db = new PDO('mysql:host=localhost;dbname=your_database', 'username', 'password');
$stmt = $db->prepare("SELECT * FROM comments WHERE post_id = ? ORDER BY created_at DESC");
$stmt->execute([$post_id]);
$comments = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($comments as $comment) {
echo '<div class="comment">';
echo '<h4>' . htmlspecialchars($comment['username']) . '</h4>';
echo '<p>' . nl2br(htmlspecialchars($comment['content'])) . '</p>';
echo '<small>' . $comment['created_at'] . '</small>';
echo '</div>';
}
?>
安全增强措施
输入验证和过滤
$username = trim(strip_tags($_POST['username']));
$content = trim(strip_tags($_POST['content'], '<a><strong><em><code>'));
防止SQL注入
$stmt = $db->prepare("INSERT INTO comments (...) VALUES (?, ?, ?, ?)");
$stmt->bindParam(1, $username, PDO::PARAM_STR);
$stmt->bindParam(2, $email, PDO::PARAM_STR);
$stmt->bindParam(3, $content, PDO::PARAM_STR);
$stmt->bindParam(4, $post_id, PDO::PARAM_INT);
分页功能实现
获取分页参数
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$per_page = 10;
$offset = ($page - 1) * $per_page;
修改查询语句
$stmt = $db->prepare("SELECT * FROM comments WHERE post_id = ? ORDER BY created_at DESC LIMIT ? OFFSET ?");
$stmt->bindValue(1, $post_id, PDO::PARAM_INT);
$stmt->bindValue(2, $per_page, PDO::PARAM_INT);
$stmt->bindValue(3, $offset, PDO::PARAM_INT);
生成分页链接
$total = $db->query("SELECT COUNT(*) FROM comments WHERE post_id = $post_id")->fetchColumn();
$pages = ceil($total / $per_page);
for ($i = 1; $i <= $pages; $i++) {
echo "<a href='post.php?id=$post_id&page=$i'>$i</a> ";
}






