PHP实现新闻评论
数据库设计
创建新闻表和评论表,新闻表存储新闻信息,评论表存储评论内容并关联新闻ID。
CREATE TABLE news (
id INT AUTO_INCREMENT PRIMARY KEY,
title VARCHAR(255) NOT NULL,
content TEXT NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
CREATE TABLE comments (
id INT AUTO_INCREMENT PRIMARY KEY,
news_id INT NOT NULL,
user_name VARCHAR(100) NOT NULL,
comment TEXT NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (news_id) REFERENCES news(id)
);
连接数据库
使用PDO连接MySQL数据库,确保安全性。
$host = 'localhost';
$dbname = 'news_site';
$username = 'root';
$password = '';
try {
$pdo = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
die("Database connection failed: " . $e->getMessage());
}
显示新闻及评论
查询特定新闻及其关联评论,按时间倒序排列。

$news_id = $_GET['id'] ?? 0;
$stmt = $pdo->prepare("SELECT * FROM news WHERE id = ?");
$stmt->execute([$news_id]);
$news = $stmt->fetch(PDO::FETCH_ASSOC);
$stmt = $pdo->prepare("SELECT * FROM comments WHERE news_id = ? ORDER BY created_at DESC");
$stmt->execute([$news_id]);
$comments = $stmt->fetchAll(PDO::FETCH_ASSOC);
提交评论处理
验证用户输入并插入新评论到数据库。
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['submit_comment'])) {
$user_name = htmlspecialchars(trim($_POST['user_name']));
$comment = htmlspecialchars(trim($_POST['comment']));
if (!empty($user_name) && !empty($comment)) {
$stmt = $pdo->prepare("INSERT INTO comments (news_id, user_name, comment) VALUES (?, ?, ?)");
$stmt->execute([$news_id, $user_name, $comment]);
header("Location: news.php?id=$news_id");
exit();
}
}
前端展示
创建简单的HTML表单和评论列表。

<h1><?= htmlspecialchars($news['title']) ?></h1>
<p><?= nl2br(htmlspecialchars($news['content'])) ?></p>
<h2>Comments</h2>
<form method="POST">
<input type="text" name="user_name" placeholder="Your name" required>
<textarea name="comment" placeholder="Your comment" required></textarea>
<button type="submit" name="submit_comment">Submit</button>
</form>
<div class="comments">
<?php foreach ($comments as $comment): ?>
<div class="comment">
<strong><?= htmlspecialchars($comment['user_name']) ?></strong>
<small><?= $comment['created_at'] ?></small>
<p><?= nl2br(htmlspecialchars($comment['comment'])) ?></p>
</div>
<?php endforeach; ?>
</div>
安全性增强
添加CSRF保护和输入验证。
session_start();
if (!isset($_SESSION['csrf_token'])) {
$_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
if (!isset($_POST['csrf_token']) || $_POST['csrf_token'] !== $_SESSION['csrf_token']) {
die('CSRF token validation failed');
}
}
在表单中添加CSRF令牌:
<input type="hidden" name="csrf_token" value="<?= $_SESSION['csrf_token'] ?>">






