資料庫設計
CREATE TABLE `messages` (
`id` INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
`pid` INT UNSIGNED DEFAULT 0 COMMENT '父留言 ID,0 為頂層留言',
`article_id` INT UNSIGNED NOT NULL COMMENT '所屬文章 ID',
`from_user` VARCHAR(50) NOT NULL COMMENT '發送者',
`to_user` VARCHAR(50) NOT NULL COMMENT '接收者(文章作者或被回覆者)',
`content` TEXT NOT NULL COMMENT '留言內容',
`status` TINYINT DEFAULT 0 COMMENT '0=未讀 1=已讀',
`created_at` INT UNSIGNED NOT NULL COMMENT '建立時間戳',
INDEX `idx_article` (`article_id`),
INDEX `idx_pid` (`pid`),
INDEX `idx_to_user_status` (`to_user`, `status`)
);
核心功能模組
1. 發表留言(頂層)
<?php
// 表單處理
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['content'])) {
$user = $_SESSION['username'] ?? 'guest';
$articleId = (int)$_POST['article_id'];
$content = trim($_POST['content']);
if ($content) {
$stmt = $pdo->prepare('
INSERT INTO messages (pid, article_id, from_user, to_user, content, created_at)
VALUES (0, ?, ?, ?, ?, ?)
');
// to_user 為文章作者,需先查詢
$author = $pdo->query("SELECT author FROM articles WHERE id = $articleId")->fetchColumn();
$stmt->execute([$articleId, $user, $author, $content, time()]);
header('Location: ' . $_SERVER['HTTP_REFERER']);
exit;
}
}
?>
2. 回覆留言(子層)
<?php
// 回覆處理
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['reply_content'], $_POST['pid'])) {
$user = $_SESSION['username'] ?? 'guest';
$pid = (int)$_POST['pid'];
$articleId = (int)$_POST['article_id'];
$content = trim($_POST['reply_content']);
if ($content) {
// 取得父留言資訊
$parent = $pdo->prepare('SELECT from_user, to_user FROM messages WHERE id = ?');
$parent->execute([$pid]);
$parent = $parent->fetch();
// 回覆對象:父留言的發送者
$toUser = $parent['from_user'];
$stmt = $pdo->prepare('
INSERT INTO messages (pid, article_id, from_user, to_user, content, created_at)
VALUES (?, ?, ?, ?, ?, ?)
');
$stmt->execute([$pid, $articleId, $user, $toUser, $content, time()]);
header('Location: ' . $_SERVER['HTTP_REFERER']);
exit;
}
}
?>
3. 讀取並渲染巢狀留言
<?php
function getMessageTree($articleId) {
global $pdo;
// 一次查詢所有留言
$stmt = $pdo->prepare('SELECT * FROM messages WHERE article_id = ? ORDER BY created_at ASC');
$stmt->execute([$articleId]);
$all = $stmt->fetchAll(PDO::FETCH_ASSOC);
// 組裝樹狀結構
$tree = [];
$map = [];
foreach ($all as $msg) {
$msg['children'] = [];
$map[$msg['id']] = &$msg; // 參考賦值
if ($msg['pid'] === 0) {
$tree[] = &$msg;
} else {
if (isset($map[$msg['pid']])) {
$map[$msg['pid']]['children'][] = &$msg;
}
}
}
return $tree;
}
function renderMessages($tree, $depth = 0) {
$html = '';
foreach ($tree as $msg) {
$html .= '<div class="msg" style="margin-left:' . ($depth * 30) . 'px">';
$html .= '<strong>' . htmlspecialchars($msg['from_user']) . '</strong> ';
$html .= '<span class="time">' . date('Y-m-d H:i', $msg['created_at']) . '</span><br>';
$html .= '<div class="content">' . nl2br(htmlspecialchars($msg['content'])) . '</div>';
// 回覆按鈕(JS 控制顯示/隱藏表單)
$html .= '<button onclick="toggleReply(' . $msg['id'] . ')">回覆</button>';
$html .= '<div id="reply-form-' . $msg['id'] . '" class="reply-form" style="display:none">';
$html .= '<form method="post">';
$html .= '<input type="hidden" name="pid" value="' . $msg['id'] . '">';
$html .= '<input type="hidden" name="article_id" value="' . $msg['article_id'] . '">';
$html .= '<textarea name="reply_content" rows="3" cols="50"></textarea><br>';
$html .= '<button type="submit">送出回覆</button>';
$html .= '</form></div>';
if (!empty($msg['children'])) {
$html .= renderMessages($msg['children'], $depth + 1);
}
$html .= '</div>';
}
return $html;
}
// 使用
$tree = getMessageTree($articleId);
echo renderMessages($tree);
?>
4. 新訊息提醒(未讀狀態)
<?php
// 顯示未讀計數
function getUnreadCount($username) {
global $pdo;
$stmt = $pdo->prepare('SELECT COUNT(*) FROM messages WHERE to_user = ? AND status = 0');
$stmt->execute([$username]);
return $stmt->fetchColumn();
}
// 標記已讀
function markAsRead($msgId, $username) {
global $pdo;
$stmt = $pdo->prepare('UPDATE messages SET status = 1 WHERE id = ? AND to_user = ?');
$stmt->execute([$msgId, $username]);
}
// 頁面頂部顯示
$unread = getUnreadCount($_SESSION['username']);
if ($unread > 0) {
echo "<div class='alert'>您有 <strong>$unread</strong> 條新訊息 <a href='messages.php'>查看</a></div>";
}
?>
前端 JS 互動(簡易版)
<script>
function toggleReply(pid) {
const form = document.getElementById('reply-form-' + pid);
form.style.display = form.style.display === 'none' ? 'block' : 'none';
}
// 可選:AJAX 送出回覆,無刷新體驗
document.querySelectorAll('.reply-form form').forEach(form => {
form.addEventListener('submit', async (e) => {
e.preventDefault();
const fd = new FormData(form);
const res = await fetch('ajax_reply.php', {method: 'POST', body: fd});
if (res.ok) location.reload(); // 簡單重整,或動態插入 DOM
});
});
</script>
擴充功能建議
- @提及通知:解析內容中的 `@username`,建立通知記錄。
- 留言編輯/刪除:作者與管理員權限控制。
- 分頁載入:大量留言時分頁或無限滾動載入。
- 表情/圖片/代碼塊:富文本編輯器整合。
- 垃圾留言過濾:關鍵字過濾、Akismet API、驗證碼。