:::

6-4 讓側邊欄的年度文章數有作用

一、資料庫的計數方法

  1. 首先,年度應該是從文章的日期去計算出來的
  2. 要從資料庫計算數量,最常用的方法就是 count() 搭配 group by 語法,例如:
    SELECT COUNT(*), `計數欄位` FROM `資料表` GROUP BY `欲計數欄位`

     

  3. 由於只要判斷年度,所以還會搭配 left() 的用法,也就是只擷取左邊 4 個數字(年度部份)
    SELECT LEFT(`日期欄位`, 4) AS Y, COUNT(*) FROM `資料表` GROUP BY Y

    SELECT YEAR(`日期欄位`) AS Y, COUNT(*) FROM `資料表` GROUP BY Y

     

二、抓出文章所有年度

  1. 由於側邊欄前後臺都會有,所以,我們可以新增一個 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;
    }

     

    1. 利用 COUNT() 搭配 GROUP BY 語法將「年度」及「文章數」都抓出來,並用 YEAR() 來取得日期欄位的年份,並用 AS 命名別名 Y (因為後面都會用到)

    2. 重點在於用fetchAll()讀出時,指定了 PDO::FETCH_KEY_PAIR 參數,也就是將取得的兩個值,一個當索引,一個當值,的放入陣列中,更好完全符合我們的需求。

  2. 修改前後台都會引入的 header.php,引入 function.php
    <?php
    require_once 'config.php';
    require_once 'vendor/autoload.php';
    require_once 'function.php';
    

     

  3. 修改 index.phpadmin.php,執行函式並將其值丟到樣板
    $smarty->assign('op', $op);
    $smarty->assign('categories', $categories);
    $smarty->assign('year_count', year_count());
    $smarty->display('index.tpl');

     

  4. 最後修改 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>
    1. $year_count foreach() 依序取出,並拆分為將年度 {$year} 及數量 {$counter}
    2. 原本是 <ul><li></li></div> 結構,因為想要用連結,故改為 <div><a></a></div> 結構,如此可以方便加入連結
    3. 在選項連結上,我們也用 index.php?year={$year} 告知 index.php 要取出 year 為某一年的文章資料
    4. 當網址有傳入 $year 參數時可以用 $smarty.get.year 取得,若是和迴圈讀到的的年度一致,就加入 active,使之變成藍底白字。
    5. 另一個情況是網址沒有傳入 $year 參數時,就改用 $smarty.now|date_format:'%Y' 取得現在的年份,若是和迴圈讀到的的年度一致,也加入 active
  5. 最後看起來像這樣:


:::

書籍目錄

展開 | 闔起

http%3A%2F%2Fcampus-xoops.tn.edu.tw%2Fmodules%2Ftad_book3%2Fpage.php%3Ftbsn%3D52%26tbdsn%3D1829

計數器

今天: 2031203120312031
昨天: 4745474547454745
總計: 7711992771199277119927711992771199277119927711992