CodeIgniter 內建的分頁類庫預設使用 URI 片段傳遞頁碼(如 /page/2),但在複雜搜尋場景下,需要保留多個 GET 參數(關鍵字、日期範圍、狀態等),傳統做法容易導致參數遺失或 URL 過長。
public function project_search() {
$this->load->library('pagination');
$this->load->model('depart_mdl');
// 合併預設搜尋條件與 GET 參數
$data = $this->get_project_data();
$get_data = $this->input->get();
$data = array_merge($data, $get_data);
// 將所有搜尋參數組裝成查詢字串
$suffix = "?name={$get_data['name']}&username={$get_data['username']}&budget={$get_data['budget']}"
. "&type={$get_data['type']}&posttime_start={$get_data['posttime_start']}"
. "&posttime_end={$get_data['posttime_end']}&purchase_type={$get_data['purchase_type']}"
. "&depart_code={$get_data['depart_code']}&project_status={$get_data['project_status']}"
. "&bidder_way={$get_data['bidder_way']}";
$config['base_url'] = site_url('project/project_search') . $suffix;
$config['total_rows'] = $this->db->count_all($this->db->dbprefix('project'));
$config['per_page'] = 10;
$config['page_query_string'] = TRUE; // 關鍵:使用 ?page=2 模式
$config['query_string_segment'] = 'page'; // 頁碼參數名
$config['uri_segment'] = 3; // 相容性設定
$this->pagination->initialize($config);
$user = $this->user_mdl->get_user_by_salary_no($this->session->userdata('salary_no'));
$this->db->from('ustc_project');
$this->db->join('ustc_admins', 'ustc_admins.salary_no = ustc_project.salary_no');
// 非管理員只能看自己部門或自己的專案
if ($user->role != 1) {
$depart_codes = explode(',', $user->grant_depart_code);
$this->db->where_in('grant_depart_code', $depart_codes);
$this->db->or_where('ustc_project.salary_no', $this->session->userdata('salary_no'));
}
// 動態疊加搜尋條件
$search_fields = ['name', 'username', 'budget', 'type', 'depart_code',
'purchase_type', 'project_status', 'bidder_way'];
foreach ($search_fields as $field) {
if (!empty($get_data[$field])) {
$this->db->like($field, $get_data[$field]);
}
}
// 日期範圍處理
if (!empty($get_data['posttime_start'])) {
$this->db->where('posttime >', strtotime($get_data['posttime_start']));
}
if (!empty($get_data['posttime_end'])) {
$this->db->where('posttime <', strtotime($get_data['posttime_end']));
}
$page_from = isset($get_data['page']) ? (int)$get_data['page'] : 0;
$this->db->order_by('posttime', 'desc');
$projects = $this->db->limit($config['per_page'], $page_from)->get()->result_array();
// 關聯資料補全:類型、採購方式、部門名稱
foreach ($projects as &$project) {
$project['type'] = $this->manage_info_mdl->get_value_by_id($project['type'])->value;
$project['purchase_type'] = $this->manage_info_mdl->get_value_by_id($project['purchase_type'])->value;
$project['depart'] = $this->depart_mdl->get_depart_by_code($project['depart_code'])->name;
}
$data['projects'] = $projects;
$data['user_role'] = $user->role;
$this->_template('project_search', $data);
}
| 配置項 | 作用 |
|---|---|
page_query_string = TRUE | 啟用 GET 參數傳遞頁碼(?page=2) |
query_string_segment | 自訂頁碼參數名稱,預設為 per_page |
base_url 包含完整查詢字串 | 確保分頁連結保留所有搜尋條件 |
count_all() 會忽略 where 條件,實際專案應使用 count_all_results() 搭配相同查詢條件$get_data,生產環境務必加入 $this->db->escape() 或使用 Query Binding