단계별 예제를 사용한 Codeigniter의 페이지 매김
데이터베이스는 살아있는 개체입니다. 시간이 지남에 따라 성장합니다. 애플리케이션을 설계할 때 사용자가 탐색해야 할 많은 레코드를 고려해야 합니다. 페이지 나누기를 통해 결과를 작고 관리하기 쉬운 부분으로 나눌 수 있습니다. 다음 이미지는 Google 검색에서 페이지 나누기의 예를 보여줍니다.
이 튜토리얼에서는 페이지 매김 라이브러리를 사용하여 CodeIgniter에서 데이터베이스 결과를 페이지 매김하는 방법을 배우게 됩니다. 이 튜토리얼에서는 여러분이 CodeIgniter Active Record의 기본 사항에 익숙하다고 가정합니다. 그렇지 않은 경우 이전 자습서를 읽을 수 있습니다. 또 다른 가정은 이미 CodeIgniter를 다운로드했다는 것입니다.
데이터베이스 구성
데이터베이스를 생성하고 여기에 더미 레코드를 삽입하는 것부터 시작하겠습니다. 이는 50개의 레코드가 포함된 단일 테이블 데이터베이스가 됩니다.
다음 스크립트를 실행하세요. MySQL 데이터베이스 작성자 테이블을 생성합니다. 50개의 더미 레코드를 삽입합니다.
CREATE SCHEMA ci_pagination; DROP TABLE IF EXISTS `authors`; CREATE TABLE `authors` ( `id` int(11) NOT NULL AUTO_INCREMENT, `first_name` varchar(50) COLLATE utf8_unicode_ci NOT NULL, `last_name` varchar(50) COLLATE utf8_unicode_ci NOT NULL, `email` varchar(100) COLLATE utf8_unicode_ci NOT NULL, `birthdate` date NOT NULL, `added` timestamp NOT NULL DEFAULT current_timestamp(), PRIMARY KEY (`id`), UNIQUE KEY `email` (`email`) ) ENGINE=InnoDB AUTO_INCREMENT=101 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
INSERT INTO `authors` (`id`, `first_name`, `last_name`, `email`, `birthdate`, `added`) VALUES (1, 'Brielle', 'O\'Hara', 'alexandre67@example.com', '1974-05-21', '1999-09-17 19:17:28'); INSERT INTO `authors` (`id`, `first_name`, `last_name`, `email`, `birthdate`, `added`) VALUES (2, 'Flavio', 'Lehner', 'mafalda85@example.net', '1971-10-14', '1998-09-09 00:25:06'); INSERT INTO `authors` (`id`, `first_name`, `last_name`, `email`, `birthdate`, `added`) VALUES (3, 'Elmira', 'Johns', 'wellington52@example.org', '1983-11-28', '2015-02-07 15:56:43'); INSERT INTO `authors` (`id`, `first_name`, `last_name`, `email`, `birthdate`, `added`) VALUES (4, 'Elza', 'Mitchell', 'marisol46@example.org', '1989-03-08', '1992-08-21 00:21:39'); INSERT INTO `authors` (`id`, `first_name`, `last_name`, `email`, `birthdate`, `added`) VALUES (5, 'Viva', 'Greenfelder', 'era94@example.com', '1995-04-17', '2017-04-30 05:55:39'); INSERT INTO `authors` (`id`, `first_name`, `last_name`, `email`, `birthdate`, `added`) VALUES (6, 'Maxwell', 'VonRueden', 'mcassin@example.net', '1994-07-01', '1996-05-08 23:30:14'); INSERT INTO `authors` (`id`, `first_name`, `last_name`, `email`, `birthdate`, `added`) VALUES (7, 'Deontae', 'Becker', 'rory.kub@example.org', '1992-02-19', '2017-07-22 11:49:15'); INSERT INTO `authors` (`id`, `first_name`, `last_name`, `email`, `birthdate`, `added`) VALUES (8, 'Sylvester', 'Christiansen', 'erohan@example.org', '1990-09-03', '2004-05-08 08:15:37'); INSERT INTO `authors` (`id`, `first_name`, `last_name`, `email`, `birthdate`, `added`) VALUES (9, 'Torrey', 'Strosin', 'adams.luciano@example.net', '1999-10-09', '2009-08-30 21:30:44'); INSERT INTO `authors` (`id`, `first_name`, `last_name`, `email`, `birthdate`, `added`) VALUES (10, 'Kelli', 'Smitham', 'daniel.catalina@example.com', '2012-11-07', '1986-01-22 20:52:57'); INSERT INTO `authors` (`id`, `first_name`, `last_name`, `email`, `birthdate`, `added`) VALUES (11, 'Abigale', 'Schuppe', 'andreanne.hayes@example.net', '2018-02-18', '1994-05-07 06:26:36'); INSERT INTO `authors` (`id`, `first_name`, `last_name`, `email`, `birthdate`, `added`) VALUES (12, 'Letha', 'Gleason', 'eldridge.heaney@example.net', '2009-02-06', '1998-05-25 04:37:54'); INSERT INTO `authors` (`id`, `first_name`, `last_name`, `email`, `birthdate`, `added`) VALUES (13, 'Sienna', 'Upton', 'monique57@example.org', '2017-08-17', '2009-08-08 19:08:10'); INSERT INTO `authors` (`id`, `first_name`, `last_name`, `email`, `birthdate`, `added`) VALUES (14, 'Harley', 'Gutkowski', 'breilly@example.net', '1987-11-30', '1998-07-31 11:08:01'); INSERT INTO `authors` (`id`, `first_name`, `last_name`, `email`, `birthdate`, `added`) VALUES (15, 'Lois', 'Bednar', 'hpouros@example.net', '2002-02-11', '2001-07-26 15:04:16'); INSERT INTO `authors` (`id`, `first_name`, `last_name`, `email`, `birthdate`, `added`) VALUES (16, 'Gail', 'McDermott', 'reina.kerluke@example.com', '1987-03-30', '2004-12-15 20:38:29'); INSERT INTO `authors` (`id`, `first_name`, `last_name`, `email`, `birthdate`, `added`) VALUES (17, 'Sydney', 'Strosin', 'dweber@example.net', '1985-04-29', '2010-08-07 08:50:35'); INSERT INTO `authors` (`id`, `first_name`, `last_name`, `email`, `birthdate`, `added`) VALUES (18, 'Anne', 'Cremin', 'fritz.schmitt@example.com', '1976-02-15', '1980-03-25 05:29:41'); INSERT INTO `authors` (`id`, `first_name`, `last_name`, `email`, `birthdate`, `added`) VALUES (19, 'Norberto', 'Bergnaum', 'franecki.javon@example.net', '1971-03-11', '1993-03-20 23:36:25'); INSERT INTO `authors` (`id`, `first_name`, `last_name`, `email`, `birthdate`, `added`) VALUES (20, 'Arvid', 'Johns', 'pschultz@example.org', '2016-01-03', '1995-04-30 17:07:15'); INSERT INTO `authors` (`id`, `first_name`, `last_name`, `email`, `birthdate`, `added`) VALUES (21, 'Bernita', 'Fay', 'arne96@example.org', '1983-12-26', '1987-02-23 16:55:28'); INSERT INTO `authors` (`id`, `first_name`, `last_name`, `email`, `birthdate`, `added`) VALUES (22, 'Gonzalo', 'Gorczany', 'velma.huels@example.com', '1987-10-19', '2016-10-18 19:25:46'); INSERT INTO `authors` (`id`, `first_name`, `last_name`, `email`, `birthdate`, `added`) VALUES (23, 'Jackie', 'Klein', 'gretchen.howe@example.com', '1971-01-20', '2010-11-16 02:58:05'); INSERT INTO `authors` (`id`, `first_name`, `last_name`, `email`, `birthdate`, `added`) VALUES (24, 'Andrew', 'Kessler', 'collins.faye@example.org', '1984-08-07', '1971-12-15 08:46:42'); INSERT INTO `authors` (`id`, `first_name`, `last_name`, `email`, `birthdate`, `added`) VALUES (25, 'Claire', 'Hudson', 'madalyn.wunsch@example.org', '1984-12-19', '1991-07-04 14:35:53'); INSERT INTO `authors` (`id`, `first_name`, `last_name`, `email`, `birthdate`, `added`) VALUES (26, 'Prudence', 'Runte', 'koch.laurie@example.net', '2008-12-27', '1985-09-30 04:57:55'); INSERT INTO `authors` (`id`, `first_name`, `last_name`, `email`, `birthdate`, `added`) VALUES (27, 'Destinee', 'Romaguera', 'tromp.tiffany@example.com', '1978-11-09', '1997-11-09 19:58:08'); INSERT INTO `authors` (`id`, `first_name`, `last_name`, `email`, `birthdate`, `added`) VALUES (28, 'Marianna', 'Harvey', 'clovis.schuppe@example.com', '2013-08-28', '1990-08-06 19:29:19'); INSERT INTO `authors` (`id`, `first_name`, `last_name`, `email`, `birthdate`, `added`) VALUES (29, 'Eloy', 'Lakin', 'wmorissette@example.net', '1989-12-08', '1974-03-16 03:21:16'); INSERT INTO `authors` (`id`, `first_name`, `last_name`, `email`, `birthdate`, `added`) VALUES (30, 'Rubie', 'McClure', 'haley.louisa@example.net', '1987-09-12', '1998-07-02 10:45:36'); INSERT INTO `authors` (`id`, `first_name`, `last_name`, `email`, `birthdate`, `added`) VALUES (31, 'Marisa', 'Stracke', 'zachary76@example.org', '1975-05-28', '1975-03-19 00:57:35'); INSERT INTO `authors` (`id`, `first_name`, `last_name`, `email`, `birthdate`, `added`) VALUES (32, 'Jacey', 'Beatty', 'dahlia.hermann@example.org', '1979-12-17', '1971-01-21 16:50:58'); INSERT INTO `authors` (`id`, `first_name`, `last_name`, `email`, `birthdate`, `added`) VALUES (33, 'Idella', 'Ruecker', 'elda.reichert@example.com', '2009-09-15', '1996-04-19 22:27:31'); INSERT INTO `authors` (`id`, `first_name`, `last_name`, `email`, `birthdate`, `added`) VALUES (34, 'Dimitri', 'Bednar', 'freida.parker@example.org', '1998-12-02', '2008-12-30 23:29:57'); INSERT INTO `authors` (`id`, `first_name`, `last_name`, `email`, `birthdate`, `added`) VALUES (35, 'Elfrieda', 'Smitham', 'padberg.rex@example.org', '2018-07-23', '1972-04-01 07:52:25'); INSERT INTO `authors` (`id`, `first_name`, `last_name`, `email`, `birthdate`, `added`) VALUES (36, 'Dwight', 'Walter', 'gmosciski@example.org', '2016-08-15', '1994-07-02 11:06:55'); INSERT INTO `authors` (`id`, `first_name`, `last_name`, `email`, `birthdate`, `added`) VALUES (37, 'Macie', 'Fay', 'uschuppe@example.net', '1976-01-29', '2005-12-13 18:44:46'); INSERT INTO `authors` (`id`, `first_name`, `last_name`, `email`, `birthdate`, `added`) VALUES (38, 'Lori', 'Kshlerin', 'mhansen@example.net', '1983-04-08', '1986-01-18 16:03:52'); INSERT INTO `authors` (`id`, `first_name`, `last_name`, `email`, `birthdate`, `added`) VALUES (39, 'Jeffry', 'Paucek', 'alisha35@example.net', '2002-10-02', '2004-03-29 07:06:03'); INSERT INTO `authors` (`id`, `first_name`, `last_name`, `email`, `birthdate`, `added`) VALUES (40, 'Yvonne', 'Bernhard', 'jaqueline21@example.net', '2017-11-04', '1986-12-15 23:55:23'); INSERT INTO `authors` (`id`, `first_name`, `last_name`, `email`, `birthdate`, `added`) VALUES (41, 'Ludwig', 'Heathcote', 'marcelino.kirlin@example.org', '1981-02-09', '2000-08-02 20:45:48'); INSERT INTO `authors` (`id`, `first_name`, `last_name`, `email`, `birthdate`, `added`) VALUES (42, 'Jadyn', 'Wiegand', 'georgianna.swift@example.net', '1982-06-16', '1980-12-05 13:09:37'); INSERT INTO `authors` (`id`, `first_name`, `last_name`, `email`, `birthdate`, `added`) VALUES (43, 'Ferne', 'Smitham', 'melany22@example.com', '1996-12-17', '1984-11-18 19:26:27'); INSERT INTO `authors` (`id`, `first_name`, `last_name`, `email`, `birthdate`, `added`) VALUES (44, 'Meta', 'Corkery', 'xharber@example.com', '1972-03-31', '2007-01-20 00:07:31'); INSERT INTO `authors` (`id`, `first_name`, `last_name`, `email`, `birthdate`, `added`) VALUES (45, 'Toni', 'Wolf', 'wyman.crystal@example.org', '2012-04-15', '1973-06-22 12:14:37'); INSERT INTO `authors` (`id`, `first_name`, `last_name`, `email`, `birthdate`, `added`) VALUES (46, 'Zack', 'Luettgen', 'deion.konopelski@example.org', '2003-05-29', '2018-11-19 05:03:21'); INSERT INTO `authors` (`id`, `first_name`, `last_name`, `email`, `birthdate`, `added`) VALUES (47, 'Kameron', 'Dietrich', 'ronaldo.torphy@example.com', '1973-05-20', '1974-09-16 20:27:17'); INSERT INTO `authors` (`id`, `first_name`, `last_name`, `email`, `birthdate`, `added`) VALUES (48, 'Zetta', 'Lebsack', 'timmothy.vandervort@example.com', '1996-11-04', '2001-03-06 01:33:01'); INSERT INTO `authors` (`id`, `first_name`, `last_name`, `email`, `birthdate`, `added`) VALUES (49, 'Benny', 'Hane', 'leone.lueilwitz@example.net', '2008-02-02', '2006-01-27 22:12:39'); INSERT INTO `authors` (`id`, `first_name`, `last_name`, `email`, `birthdate`, `added`) VALUES (50, 'Evans', 'Gleason', 'ccummerata@example.org', '1999-09-09', '1990-09-26 17:50:11');
이제 데이터베이스를 성공적으로 생성하고 여기에 더미 레코드를 삽입했으므로 데이터베이스와 통신하도록 CodeIgniter 애플리케이션을 구성해 보겠습니다.
application/config/database.php 열기
다음과 유사한 데이터베이스 연결 매개변수를 설정하세요.
$db['default'] = array( 'dsn' => '', 'hostname' => 'localhost', 'username' => 'root', 'password' => 'melody', 'database' => 'ci_pagination', 'dbdriver' => 'mysqli', 'dbprefix' => '', 'pconnect' => FALSE, 'db_debug' => (ENVIRONMENT !== 'production'), 'cache_on' => FALSE, 'cachedir' => '', 'char_set' => 'utf8', 'dbcollat' => 'utf8_general_ci', 'swap_pre' => '', 'encrypt' => FALSE, 'compress' => FALSE, 'stricton' => FALSE, 'failover' => array(), 'save_queries' => TRUE );
이리,
- 'hostname' => 'localhost', 데이터베이스의 호스트 이름을 설정합니다.
- 'username' => 'root', 데이터베이스 이름을 지정합니다.
- 'password' => 'openseseme', 데이터베이스 비밀번호를 설정합니다.
- 'database' => 'ci_pagination'은 데이터베이스 이름을 지정합니다.
또한 애플리케이션이 시작될 때 데이터베이스 라이브러리를 자동 로드합니다. 그걸하자. application/config/autoload.php 열기
아래 코드에 표시된 대로 데이터베이스 라이브러리를 로드합니다.
$autoload['libraries'] = array('database');
이것이 데이터베이스 구성의 전부입니다.
이제 페이지 매김을 위한 데이터베이스 모델을 작업해 보겠습니다.
CodeIgniter 페이지 매김 데이터베이스 모델
애플리케이션/모델에 새로운 모델 Authors_model을 생성합니다.
다음 코드를 추가하세요
<?php class Authors_model extends CI_Model { protected $table = 'authors'; public function __construct() { parent::__construct(); } public function get_count() { return $this->db->count_all($this->table); } public function get_authors($limit, $start) { $this->db->limit($limit, $start); $query = $this->db->get($this->table); return $query->result(); } }
이리,
- 보호된 $table = '저자'; 모델의 데이터베이스 테이블 이름을 정의하는 보호 변수를 정의합니다.
- 공용 함수 __construct() {…}는 상위 생성자 메서드를 호출합니다.
- public function get_count() {…}는 데이터베이스 테이블의 총 레코드를 반환합니다. 이는 페이지 매기기 목적에 필요합니다.
- public function get_authors($limit, $start) {…}는 데이터베이스에서 페이지가 매겨진 결과를 검색하는 데 사용되는 메서드를 정의합니다. 한계와 시작점을 전달하겠습니다. 제한은 반환될 총 레코드 수를 정의하는 반면, start는 건너뛰어야 하는 레코드 수를 정의합니다.
이것이 우리 데이터베이스 모델의 전부입니다. 이제 페이지를 매긴 결과에 응답할 경로를 만들어 보겠습니다.
CodeIgniter 페이지 매김 경로
application/config/routes.php에서 경로 파일을 엽니다.
다음 경로를 추가하세요
$route['authors/(:num)'] = 'authors';
이리,
- 숫자의 선택적 매개변수를 허용하는 경로 작성자를 정의합니다. 선택적 매개변수는 여는 괄호와 닫는 괄호를 사용하여 정의합니다. 정의된 경로는 Authors 컨트롤러에서 index 메서드를 호출합니다.
이제 페이지를 매긴 결과를 위해 컨트롤러로 이동해 보겠습니다.
CodeIgniter 페이지 매김 컨트롤러
application/controllers 디렉토리에 새로운 파일 Authors.php를 생성합니다.
다음 코드를 추가하세요
<?php defined('BASEPATH') OR exit('No direct script access allowed'); class Authors extends CI_Controller { public function __construct() { parent:: __construct(); $this->load->helper('url'); $this->load->model('authors_model'); $this->load->library("pagination"); } public function index() { $config = array(); $config["base_url"] = base_url() . "authors"; $config["total_rows"] = $this->authors_model->get_count(); $config["per_page"] = 10; $config["uri_segment"] = 2; $this->pagination->initialize($config); $page = ($this->uri->segment(2)) ? $this->uri->segment(2) : 0; $data["links"] = $this->pagination->create_links(); $data['authors'] = $this->authors_model->get_authors($config["per_page"], $page); $this->load->view('authors/index', $data); } }
이리,
- class Authors는 CI_Controller를 확장합니다. {…} CI_Controller 클래스를 확장하는 Authors 클래스를 정의합니다.
- public function __construct() {…} 이 메서드는 상위 생성자를 초기화하고 URL 도우미, 작성자 모델 및 페이지 매기기 라이브러리를 로드합니다.
- public function index() {…}는 경로 작성자에게 응답하는 메서드를 정의합니다.
- $config[“base_url”] = base_url() . “저자”; 페이지 매김 링크를 생성하는 데 사용될 페이지 매김 URL을 설정합니다.
- $config[“total_rows”] = $this->authors_model->get_count(); 페이지를 매겨야 하는 전체 행을 설정합니다. 값은 get_count 메소드를 호출하여 작성자 모델에서 검색됩니다.
- $config[“per_page”] = 10; 페이지당 표시되어야 하는 행을 정의합니다.
- $config[“uri_segment”] = 2; 레코드를 건너뛰는 데 사용될 값이 포함된 URL 세그먼트를 지정합니다.
- $this->페이지 매김->초기화($config); 우리가 정의한 구성 배열 값을 사용하여 페이지 매김 라이브러리를 초기화하고 위 값을 할당합니다.
- $page = ($this->uri->segment(2)) ? $this->uri->segment(2) : 0; URI의 두 번째 세그먼트에 건너뛰기 번호가 설정되어 있는지 확인하고 설정되지 않은 경우 $page 변수에 값 0이 할당됩니다.
- $data[“links”] = $this->페이지 매김->create_links(); 페이지 매김 링크를 생성하고 이를 $data 배열 변수의 링크 키에 할당합니다.
- data['authors'] = $this->authors_model->get_authors($config[“per_page”], $page); 페이지가 매겨진 작성자 레코드를 검색하여 $data 배열 변수의 작성자 키에 할당합니다.
- $this->load->view('저자/색인', $data); 작성자 디렉토리에 인덱스 뷰를 로드하고 배열 변수 $data를 전달합니다.
이것이 우리 모델의 전부입니다. 이제 데이터베이스 결과를 표시할 뷰를 만들어 보겠습니다.
애플리케이션/뷰에 새 디렉토리 작성자를 생성합니다.
application/views/authors/index.php에 새 파일 index.php를 만듭니다.
다음 코드를 추가하세요
<!DOCTYPE html> <html> <head> <title>CodeIgniter Pagination</title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bulma/0.7.2/css/bulma.min.css"> </head> <body> <div class="container"> <h3 class="title is-3">CodeIgniter Database Pagination</h3> <div class="column"> <table class="table is-bordered is-striped is-narrow is-hoverable is-fullwidth"> <thead> <tr> <th>ID</th> <th>Contact Name</th> <th>Contact Number</th> <th>Email</th> <th>City</th> </tr> </thead> <tbody> <?php foreach ($authors as $author): ?> <tr> <td><?= $author->id ?></td> <td><?= $author->first_name ?></td> <td><?= $author->last_name ?></td> <td><?= $author->email ?></td> <td><?= $author->birthdate ?></td> </tr> <?php endforeach; ?> </tbody> </table> <p><?php echo $links; ?></p> </div> </div> </body> </html>
이리,
- $authors 변수의 결과를 반복하고 결과를 테이블에 인쇄합니다.
- 테이블 하단에 페이지 매김 링크를 인쇄합니다.
이제 애플리케이션을 시작하고 결과를 살펴보겠습니다.
이 튜토리얼에서는 내장된 PHP 웹 서버를 사용하지만 지원하는 모든 웹 서버를 사용할 수 있습니다. PHP.
터미널 열기
다음 명령을 실행하십시오
cd C:\Sites\ci-app php -S localhost:3000
이리,
- 위 명령은 애플리케이션 코드 디렉터리를 탐색하고 포트 3000에서 내장 서버를 시작합니다.
참고: 애플리케이션 경로는 CodeIgniter를 다운로드한 경로와 일치해야 합니다. 이를 위해 컴퓨터에 사용 가능한 포트 번호를 사용할 수 있습니다. 포트 3000을 사용할 필요는 없습니다.
웹 브라우저를 열고 다음 URL을 로드하세요.
http://localhost:3000/authors
다음과 유사한 결과를 얻을 수 있어야 합니다.
요약
이 튜토리얼에서는 페이지 매김의 기본 사항을 다루고 페이지 매김 라이브러리를 활용했습니다. CodeIgniter 이를 사용하여 데이터베이스 결과에 페이지를 매기는 애플리케이션을 만들었습니다.