需求:PHP 從 MySQL 讀取數據,前端頁面顯示「單圖文」或「多圖文」兩種佈局。核心難點在於**如何根據圖片數量動態選擇模板**。本文給出數據庫設計、查詢邏輯、模板渲染完整方案。
-- 文章主表
CREATE TABLE articles (
id INT PRIMARY KEY AUTO_INCREMENT,
title VARCHAR(255),
content TEXT,
type TINYINT DEFAULT 1 -- 1單圖 2多圖 (冗餘字段,便於查詢)
);
-- 圖片關聯表 (一篇文章多張圖)
CREATE TABLE article_images (
id INT PRIMARY KEY AUTO_INCREMENT,
article_id INT,
image_url VARCHAR(500),
sort_order INT DEFAULT 0,
FOREIGN KEY (article_id) REFERENCES articles(id)
);
$sql = "SELECT a.*, COUNT(ai.id) as img_count
FROM articles a
LEFT JOIN article_images ai ON a.id = ai.article_id
GROUP BY a.id
ORDER BY a.id DESC";
$stmt = $pdo->query($sql);
$articles = $stmt->fetchAll(PDO::FETCH_ASSOC);
// 為每篇文章附加圖片列表
foreach ($articles as &$art) {
$imgSql = "SELECT image_url FROM article_images WHERE article_id = ? ORDER BY sort_order";
$imgStmt = $pdo->prepare($imgSql);
$imgStmt->execute([$art['id']]);
$art['images'] = $imgStmt->fetchAll(PDO::FETCH_COLUMN);
// 根據圖片數動態標記類型 (或用資料庫 type 字段)
$art['layout_type'] = count($art['images']) > 1 ? 'multi' : 'single';
}
<!-- 單圖文模板 -->
<div class="article-single">
<h3><?= htmlspecialchars($art['title']) ?></h3>
<img src="<?= $art['images'][0] ?? 'default.jpg' ?>" alt="">
<p><?= mb_substr($art['content'], 0, 100) ?>...</p>
</div>
<!-- 多圖文模板 -->
<div class="article-multi">
<h3><?= htmlspecialchars($art['title']) ?></h3>
<div class="img-group">
<?php foreach ($art['images'] as $img): ?>
<img src="<?= $img ?>" alt="">
<?php endforeach; ?>
</div>
</div>
<!-- 控制器邏輯 -->
<?php foreach ($articles as $art): ?>
<?php if ($art['layout_type'] === 'multi'): ?>
<?php include 'template_multi.php'; ?>
<?php else: ?>
<?php include 'template_single.php'; ?>
<?php endif; ?>
<?php endforeach; ?>
JOIN + GROUP_CONCAT 或單獨查所有圖片再 array_group_by 組裝,僅 2 次查詢。若圖片 URL 以逗號/分號存單字段:
$urls = explode(',', $art['image_urls']);
$art['images'] = array_filter(array_map('trim', $urls));
$art['layout_type'] = count($art['images']) > 1 ? 'multi' : 'single';
核心邏輯不變:遍歷數據 → 統計圖片數 → 選擇模板 → 渲染。