:::

9-3 加入搜尋功能

  1. 我們的搜尋框目前長這樣:
    <form class="d-flex" action="index.php" method="GET">
        <input class="form-control me-2" type="search" placeholder="搜尋" aria-label="Search" name="search">
        <button class="btn btn-outline-success" type="submit">
            <i class="fas fa-search"></i>
        </button>
    </form>

     

  2. 也就是index.php會用GET的方式接收到一個名為search的變數,因此,我們先過濾一下(順便偷渡一下$school 變數,用來列出某間學校的文章用):
    $search = filter_input_var('search');
    $school= filter_input_var('school');

     

  3. 接著麻煩事讓AI代勞
    請修改以下的 getTotalCount() 及 all() 函數,加入$search及$school兩個參數
    $search 用來當作關鍵字,若有值的時候,就搜尋 news_title 及 news_content 欄位中有該關鍵字的資料
    $school 若是有值的時候,就搜尋 school_name 欄位中有該值的資料
    $search和$school不會同時有值
    
    function getTotalCount(): int
    {
        global $pdo;
        $stmt = $pdo->query("SELECT COUNT(*) FROM school_news");
        return (int) $stmt->fetchColumn();
    }
    
    function all(int $start = 0, int $limit = 10): array
    {
        global $pdo;
    
        $query = "SELECT * FROM school_news ORDER BY report_date DESC LIMIT ?, ?";
    
        $stmt = $pdo->prepare($query);
        $stmt->bindValue(1, $start, PDO::PARAM_INT);
        $stmt->bindValue(2, $limit, PDO::PARAM_INT);
        $stmt->execute();
    
        $results = [];
    
        while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
            // 處理JSON欄位
            if (isset($row['media']) && !empty($row['media'])) {
                $row['media'] = json_decode($row['media'], true);
            }
    
            // XSS過濾
            array_walk_recursive($row, function (&$item) {
                if (is_string($item)) {
                    $item = htmlspecialchars($item, ENT_QUOTES, 'UTF-8');
                }
            });
    
            $row['media_json'] = convertMediaToJson($row['media']);
            $row['main_image'] = array_key_first($row['media']);
            $row['summary'] = truncate_string($row['news_content'], 200);
            $row['youtube'] = '';
            if ($row['youtube_url']) {
                $row['youtube'] = getYoutubeInfo($row['youtube_url']);
            }
    
            $results[] = $row;
        }
    
        return $results;
    }

     

  4. 我們將得到的新函數取代原有函數
    function getTotalCount(?string $search = null, ?string $school = null): int
    {
        global $pdo;
    
        $query = "SELECT COUNT(*) FROM school_news";
        $params = [];
    
        if ($search !== null) {
            $query .= " WHERE (news_title LIKE ? OR news_content LIKE ?)";
            $params[] = "%$search%";
            $params[] = "%$search%";
        } elseif ($school !== null) {
            $query .= " WHERE school_name LIKE ?";
            $params[] = "%$school%";
        }
    
        $stmt = $pdo->prepare($query);
        $stmt->execute($params);
        return (int) $stmt->fetchColumn();
    }
    
    function all(int $start = 0, int $limit = 10, ?string $search = null, ?string $school = null): array
    {
        global $pdo;
    
        $query = "SELECT * FROM school_news";
        $params = [];
    
        if ($search !== null) {
            $query .= " WHERE (news_title LIKE ? OR news_content LIKE ?)";
            $params[] = "%$search%";
            $params[] = "%$search%";
        } elseif ($school !== null) {
            $query .= " WHERE school_name LIKE ?";
            $params[] = "%$school%";
        }
    
        $query .= " ORDER BY report_date DESC LIMIT ?, ?";
        $params[] = $start;
        $params[] = $limit;
    
        $stmt = $pdo->prepare($query);
        
        // Bind parameters
        foreach ($params as $key => $value) {
            $stmt->bindValue($key + 1, $value, is_int($value) ? PDO::PARAM_INT : PDO::PARAM_STR);
        }
        
        $stmt->execute();
    
        $results = [];
    
        while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
            // 處理JSON欄位
            if (isset($row['media']) && !empty($row['media'])) {
                $row['media'] = json_decode($row['media'], true);
            }
    
            // XSS過濾
            array_walk_recursive($row, function (&$item) {
                if (is_string($item)) {
                    $item = htmlspecialchars($item, ENT_QUOTES, 'UTF-8');
                }
            });
    
            $row['media_json'] = convertMediaToJson($row['media']);
            $row['main_image'] = array_key_first($row['media']);
            $row['summary'] = truncate_string($row['news_content'], 200);
            $row['youtube'] = '';
            if ($row['youtube_url']) {
                $row['youtube'] = getYoutubeInfo($row['youtube_url']);
            }
    
            $results[] = $row;
        }
    
        return $results;
    }
    

     

  5. 最後修改一下 index.php 的流程,在計算總數以及列出所有文章部份,都加入 $search, $school 兩個參數,搜尋的功能莫名其妙就完了囉!
    switch ($op) {
    
        ...略...
    
        default:
            if (!empty($id)) {
                ...略...
            } else {
    
                ...略...
    
                // 獲取總記錄數
                $totalCount = getTotalCount($search, $school);
    
                ...略...
                $smarty->assign('all_news', all($offset, $perPage, $search, $school));
                $op = "main";
            }
            $smarty->assign('aside_news', all(0, 15));
            break;
    }

     


:::

書籍目錄

展開 | 闔起

http%3A%2F%2Fcampus-xoops.tn.edu.tw%2Fmodules%2Ftad_book3%2Fpage.php%3Ftbdsn%3D2041%26tbsn%3D55

計數器

今天: 2787278727872787
昨天: 2259225922592259
總計: 7951585795158579515857951585795158579515857951585