php实现评论
PHP 实现评论功能
评论功能是网站常见的交互模块,可以通过 PHP 结合数据库实现。以下是实现评论功能的关键步骤和代码示例。
数据库设计
创建一个简单的评论表,存储评论内容、用户信息和时间戳。

CREATE TABLE comments (
id INT AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(50) NOT NULL,
comment TEXT NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
前端表单
创建一个简单的 HTML 表单,用于提交评论。

<form action="post_comment.php" method="post">
<input type="text" name="username" placeholder="Your Name" required>
<textarea name="comment" placeholder="Your Comment" required></textarea>
<button type="submit">Submit</button>
</form>
处理评论提交
创建 post_comment.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);
$username = $_POST['username'];
$comment = $_POST['comment'];
$stmt = $pdo->prepare("INSERT INTO comments (username, comment) VALUES (:username, :comment)");
$stmt->bindParam(':username', $username);
$stmt->bindParam(':comment', $comment);
$stmt->execute();
header("Location: comments.php");
} catch (PDOException $e) {
echo "Error: " . $e->getMessage();
}
?>
显示评论
创建 comments.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);
$stmt = $pdo->query("SELECT * FROM comments ORDER BY created_at DESC");
$comments = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($comments as $comment) {
echo "<div class='comment'>";
echo "<h4>" . htmlspecialchars($comment['username']) . "</h4>";
echo "<p>" . htmlspecialchars($comment['comment']) . "</p>";
echo "<small>" . $comment['created_at'] . "</small>";
echo "</div>";
}
} catch (PDOException $e) {
echo "Error: " . $e->getMessage();
}
?>
安全注意事项
- 使用
htmlspecialchars()防止 XSS 攻击。 - 使用预处理语句防止 SQL 注入。
- 对用户输入进行验证和过滤。
扩展功能
- 添加回复功能,扩展数据库表结构。
- 实现分页显示评论。
- 添加用户认证,确保评论者身份真实。
通过以上步骤,可以快速实现一个基础的评论功能,并根据需求进一步扩展。






