:::
6-4 讓側邊欄的年度文章數有作用
一、資料庫的計數方法
- 首先,年度應該是從文章的日期去計算出來的
- 要從資料庫計算數量,最常用的方法就是
count()搭配group by語法,例如:SELECT COUNT(*), `計數欄位` FROM `資料表` GROUP BY `欲計數欄位` - 由於只要判斷年度,所以還會搭配
left()的用法,也就是只擷取左邊 4 個數字(年度部份)SELECT LEFT(`日期欄位`, 4) AS Y, COUNT(*) FROM `資料表` GROUP BY Y或
SELECT YEAR(`日期欄位`) AS Y, COUNT(*) FROM `資料表` GROUP BY Y
二、抓出文章所有年度
- 由於側邊欄前後臺都會有,所以,我們可以新增一個
function.php,將函式放裡面(順便將dd()也移過去):<?php // 年度文章數 function year_count() { global $pdo; try { $stmt = $pdo->prepare("SELECT YEAR(date) AS Y, COUNT(*) FROM news GROUP BY Y ORDER BY Y DESC"); $stmt->execute(); $year_count = $stmt->fetchAll(PDO::FETCH_KEY_PAIR); } catch (PDOException $e) { die("取得年度文章數失敗:" . $e->getMessage()); } return $year_count; }-
利用
COUNT()搭配GROUP BY語法將「年度」及「文章數」都抓出來,並用YEAR()來取得日期欄位的年份,並用AS命名別名Y(因為後面都會用到) -
重點在於用
fetchAll()讀出時,指定了PDO::FETCH_KEY_PAIR參數,也就是將取得的兩個值,一個當索引,一個當值,的放入陣列中,更好完全符合我們的需求。
-
- 修改前後台都會引入的
header.php,引入function.php:<?php require_once 'config.php'; require_once 'vendor/autoload.php'; require_once 'function.php'; - 修改
index.php及admin.php,執行函式並將其值丟到樣板$smarty->assign('op', $op); $smarty->assign('categories', $categories); $smarty->assign('year_count', year_count()); $smarty->display('index.tpl'); - 最後修改
templates/index_side.tpl<div class="list-group"> {foreach $year_count as $year => $counter} <a href="index.php?year={$year}" class="list-group-item list-group-item-action d-flex justify-content-between align-items-center {if (isset($smarty.get.year) && $smarty.get.year == $year) || (!isset($smarty.get.year) && $smarty.now|date_format:'%Y' == $year)}active{/if}"> {$year} <span class="badge bg-success badge-pill">{$counter}</span> </a> {/foreach} </div>- 將
$year_count用foreach()依序取出,並拆分為將年度{$year}及數量{$counter} - 原本是
<ul><li></li></div>結構,因為想要用連結,故改為<div><a></a></div>結構,如此可以方便加入連結 - 在選項連結上,我們也用
index.php?year={$year}告知index.php要取出year為某一年的文章資料 - 當網址有傳入
$year參數時可以用$smarty.get.year取得,若是和迴圈讀到的的年度一致,就加入active,使之變成藍底白字。 - 另一個情況是網址沒有傳入
$year參數時,就改用$smarty.now|date_format:'%Y'取得現在的年份,若是和迴圈讀到的的年度一致,也加入active。
- 將
-
最後看起來像這樣:

6-3 讓搜尋框有作用