49 lines
1.6 KiB
PHP
49 lines
1.6 KiB
PHP
<?php
|
|
// 需要获取的参数
|
|
$articleId = isset($_GET['id']) ? sanitizeInput($_GET['id']) : ''; // 文章id
|
|
|
|
$sql = "SELECT id, title, content, DATE_FORMAT(created_at, '%Y-%m-%d') AS publishDate
|
|
FROM articles
|
|
WHERE id = :id";
|
|
|
|
$stmt = $pdo->prepare($sql);
|
|
$stmt->execute([':id' => $articleId]);
|
|
$article = $stmt->fetch();
|
|
|
|
if ($article) {
|
|
|
|
// 查询评论
|
|
$commentSql = "SELECT c.id, u.username AS author, u.email AS avatarUrl, c.content
|
|
FROM comments c
|
|
JOIN users u ON c.user_id = u.id
|
|
WHERE c.article_id = :article_id
|
|
ORDER BY c.created_at ASC";
|
|
|
|
$commentStmt = $pdo->prepare($commentSql);
|
|
$commentStmt->execute([':article_id' => $articleId]);
|
|
$comments = $commentStmt->fetchAll();
|
|
|
|
// 构建最终的JSON数据
|
|
$result = [
|
|
'article' => [
|
|
'title' => $article['title'],
|
|
'author' => 'admin', // TODO:
|
|
'publishDate' => $article['publishDate'],
|
|
'content' => $article['content']
|
|
],
|
|
'comments' => array_map(function ($comment) {
|
|
return [
|
|
'id' => $comment['id'],
|
|
'author' => $comment['author'],
|
|
'avatarUrl' => $comment['avatarUrl'] ? $comment['avatarUrl'] : '/placeholder.svg?height=40&width=40',
|
|
'content' => $comment['content']
|
|
];
|
|
}, $comments)
|
|
];
|
|
|
|
// 输出JSON
|
|
header('Content-Type: application/json');
|
|
echo json_encode($result, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
|
|
} else {
|
|
echo json_encode(['error' => 'Article not found'], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
|
|
} |