:::

6-1 只顯示某一分類文章

  1. 為了讓文章可以篩選,我們修改 index.php,先進行 $category 的變數過濾,並將 $category 作為新參數,以便在函數中可以根據該值來篩選文章。
    // 變數過濾
    $id = isset($_REQUEST['id']) ? (int) $_REQUEST['id'] : 0;
    $op = isset($_REQUEST['op']) ? htmlspecialchars($_REQUEST['op']) : 'index';
    $category = isset($_REQUEST['category']) ? (int) $_REQUEST['category'] : 0;

     

  2. 流程部份也要加進去該參數,才能針對某一分類取得新聞或計算文章數量(必填的參數放前面)

    // 預設為文章列表
    default:
        list($all_news, $paginator) = index($category, $perPage);
        $smarty->assign('all_news', $all_news);
        $smarty->assign('paginator', $paginator);
        break;

     

  3. 修改 index() 函式,多加一個 $category 參數,需要判斷有無 $category 的值採取不同SQL語法

    // 列出所有文章
    function index($category = 0, $perPage = 10)
    {
        global $pdo;
        // 計算總資料數
        try {
            if ($category) {
                $stmt = $pdo->prepare('SELECT count(*) FROM `news` WHERE `category`=?');
                $stmt->execute([$category]);
            } else {
                $stmt = $pdo->prepare('SELECT count(*) FROM `news`');
                $stmt->execute();
            }
            list($totalCount) = $stmt->fetch(PDO::FETCH_NUM);
            // 產生分頁物件
            $pagination = new Pagination(['totalCount' => $totalCount, 'perPage' => $perPage]);
            // 產生分頁工具列
            ob_start();
            Paginator::widget(['pagination' => $pagination]);
            $paginator = ob_get_clean();
        } catch (PDOException $e) {
            die("計算總資料數失敗:" . $e->getMessage());
        }
    
        try {
            if ($category) {
                $stmt = $pdo->prepare('SELECT * FROM `news` WHERE `category`=? ORDER BY `date` DESC LIMIT ?, ?');
                $stmt->execute([$category, $pagination->offset, $pagination->limit]);
            } else {
                $stmt = $pdo->prepare('SELECT * FROM `news` ORDER BY `date` DESC LIMIT ?, ?');
                $stmt->execute([$pagination->offset, $pagination->limit]);
            }
            $all_news = [];
            $news = $stmt->fetchAll();
            foreach ($news as $row) {
                $media = $row['media'];
                unset($row['media']);
                $row = array_map('htmlspecialchars', $row);
                $row['files'] = json_decode($media, true);
                $all_news[] = $row;
            }
    
        } catch (PDOException $e) {
            echo "資料庫連接錯誤:" . $e->getMessage();
        }
        return [$all_news, $paginator];
    }

     

  4. 如此,便能列出不同分類文章:

     

 


:::

書籍目錄

展開 | 闔起

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

計數器

今天: 1489148914891489
昨天: 1416141614161416
總計: 7340136734013673401367340136734013673401367340136