PinoyTech.org

CodeIgniter, Kohana, Mootools, jQuery and CSS

Pagination with CodeIgniter

Posted by teejay on April 13, 2009

I've often see forum posts asking why the Pagination class isn't working. I decided to create a tutorial on the Pagination class for those who need to learn about the pagination class.

One important thing you need to learn is that the Pagination class doesn't do the querying for you. It doesn't 'connect' to the database like most pagination classes.

The Pagination class ONLY creates the links for navigation.

Let's now start with the pagination tutorial. This tutorial assumes that you have connected your CodeIgniter application to the database.

First, we need to create a table.

CREATE TABLE IF NOT EXISTS `articles` (
  `id` int(11) NOT NULL auto_increment,
  `title` varchar(50) NOT NULL,
  `content` text NOT NULL,
  PRIMARY KEY  (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

Next, we create our own Model for our articles table.

<?php

class Articles_model extends Model {

 function Articles_model()
 {
  parent::Model();
 }

 function get_posts($limit = NULL, $offset = NULL)
 {
  $this->db->limit($limit, $offset);
  return $this->db->get('posts');
 }

 function count_posts()
 {
  return $this->db->count_all_results('posts');
 }

The method Articles_model() is the constructor. In PHP 4, constructors are named after the class they are located in.

The method get_posts(), retrieves the information from the database. Notice that it has parameters for limiting and the offset of returned rows.

The method count_posts(), retrieves the total number of posts available in the table.

Next on our list is creating the controller function.

<?php

class Posts extends Controller {

 function Posts()
 {
  parent::Controller();
 }

 function manage()
 {
   $this->load->model('posts_model');
   $per_page = 10;
   $total = $this->posts_model->count_posts();
   $data['posts'] = $this->posts_model->get_posts($per_page, $this->uri->segment(3));

   $base_url = site_url('posts/manage');
   $config['base_url'] = $base_url;
   $config['total_rows'] = $total;
   $config['per_page'] = $per_page;
   $config['uri_segment'] = '3';

   $this->pagination->initialize($config); 
   $this->load->view('admin/posts/manage', $data);
 }

Copy and paste and do not worry if you don't understand that chunk of code yet. We will get back to that later on.

We should consider how, CodeIgniter generates URLs. For example, our sample creates the following URL if you haven't applied any routing configuration.

http://www.yoursite.com/index.php/post/manage

If you knew that, very good because it will be needed in our pagination tutorial and whenever you use the pagination class.

The very first part of the method manage() are as follows:

$this->load->model('posts_model');
$per_page = 10;
$total = $this->posts_model->count_posts();
$data['posts'] = $this->posts_model->get_posts($per_page, (int) $this->uri->segment(3));

The first statement loads the model, posts_model. It is required if you will be accessing any of its methods. The $per_page variable is the number of posts we want to retrieve on every page. The variable, $total gets the total number of posts in the table as seen in the posts_model method, count_posts() .

$data['posts'] is a bit more complex. Remember that with this method, we will generation this:

http://www.yoursite.com/post/manage

$this->uri->segment(3) would get the value of the uri segment after the segment, 'manage'. Right now, there is nothing. So we get 0 (zero) which will mean that we will start the offset on 0 (zero) and retrieve 10 rows.

Next stop is the pagination config.

$base_url = site_url('posts/manage');
$config['base_url'] = $base_url;
$config['total_rows'] = $total;
$config['per_page'] = $per_page;
$config['uri_segment'] = '3';

$this->pagination->initialize($config); 

The $base_url will be the 'base' url that will be used for generating pagination links. With this $base_url value we would get:

http://www.yoursite.com/post/manage

When we click on the 'next' link on the CodeIgniter Pagination links, we will get:

http://www.yoursite.com/post/manage/10

Now, we can easily know what the SQL will be. Remember that we will be retrieving the posts with offset equals the value after the segment, 'manage' and right now we have 10. Now we will be retrieving 10 records with the offset of 10.

The next thing we need to do is to pass the 'limited' number of posts to the 'View' like so.

  $this->load->view('admin/posts/manage', $data);
In the View, loop over the results:
foreach ($posts->results() as $post):
    echo $post->title, '<br />';
    echo $post->content;
endforeach;

This would effectively loop through the records to be outputted to the browser. The final part is creating the Pagination links by typing this in the View:

<?php echo $this->pagination->create_links(); ?>

We are done!

This can be easily modified to other setups when routing, etc.

Categories: Web Development

Tags: codeigniter, pagination

18 Comments

reyn

Thanks,/. nice tutorial,/ im new to OOP PHP and I got it now.,,.

June 7th 2009

Thorpe

I’m glad it helped someone.

June 9th 2009

hoa pham

It’s really good. Can you post the example file for reader can download

July 25th 2009

Ari

Thx , This tutorial helped me

August 1st 2009

sai

very useful

August 12th 2009

Nicolas

Hola,
con la paginacion me estoy sacando una cana. En resumen, quiero listar mis usuarios del sistema, con la paginacion del CI. Ahora, cuando ya le paso los parametros de configuracion e imprimo los links de paginacion al momento de hacer click en el enlace, me sale un 404 donde dice q no existe la pagina. Entonces, no se si pueda ser apartir del .htaccess o de algo que este omitiendo. Lo que se es que los links me los esta mostrando de la siguiente forma: http://www.connexion21.com/citrinet/admin/usuarios.ctx&offset=3 (Observen el “&” despues del sufijo “.ctx”, deberia ser un “?” ). Mi codigo del index es:
——————————
$num = (int) $this->uri->segment(1);
$config[‘base_url’] = site_url(“admin/usuarios”);
$config[‘per_page’] = 3;
/*Aqui va el query, igual el numero de registros se trae de la tabla*/
$config[‘total_rows’] = (int)$this->db->count_all(“usuarios”);

y el .htaccess es:

  RewriteEngine On
  RewriteCond %{REQUEST_URI} ^system.*
  RewriteRule ^(.*)$ /index.php?/$1 [L]
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteRule ^(.*)$ index.php?/$1 [L]


mi correo es: rios.nicolas@gmail.com

Espero sus comentarios, es muy importante tener esto ok. Gracias

August 27th 2009

trashman

code igniter made it so easy when it comes to pagination because it has it;s own library. All you have to do is to call the libraries..thanks for the info. I hope i can find other filipinos who explored code igniter..=)

September 2nd 2009

Thorpe

I’m really glad that you are finding codeigniter pagination very easy.

Join in the fun at the codeigniter forums.

September 7th 2009

Thorpe Obazee

I’m real sorry for the comments that don’t show up right. I’m on my way to fixing this.

October 29th 2009

Thorpe Obazee

The comments are at least readable now :)

October 29th 2009

Martin

what a nice blog dear. I never seen such a quite attractive and useful blog after seeing it. I will pray for your success and also appreciate you at your great step that you have taken toward your bright future.mortgages.Thanks a lot again.

December 21st 2009

PHPcoder

Missing something…
table name..model name and controller

December 31st 2009

Mahmuda Begum

I add the pagination class just as u said…but when i’m browsing the link below, or next link,
http://localhost/ring/home/searchall/5
then it is getting no page…just error is occurring..
here, “ring” is my project name, ‘home’ controller and “searchall” is my function. 
Have u any idea why this may can occur??

January 3rd 2010

ciier

@simon,
checkout $config[‘uri_segment’]
for your example posted, set it to:
$config[‘uri_segment’] = 4;

February 25th 2010

Benedict

@Mahmuda Begum - http://localhost/ring/home/searchall/5
you will need to replace
$config[‘uri_segment’] = ‘3’;
with
$config[‘uri_segment’] = ‘4’;
because ‘ring’ is ‘1’ in the URI
then home is ‘2’
searchall is ‘3’
5 which is the offset is located in the ‘4’

January 31st 2010

Kabir

How I can create subcategory pagination in codeigniter >

February 5th 2010

Khalil

Helpful Tutorial Thanks, now waiting for ajax pagination with codeigniter

February 5th 2010

Simon

Great tutorial, thanks.

Do you have any hints when using the routing?

For example, I have www.domain.com/category/(:any)/page/(:num) routing to category/page/$1/$2

The pagination actually works fine, but the pagination links do not.  They always stay static.

I’ve set my base_url to site_url(‘category/’.$data[‘searching_for’].’/page/’)

February 16th 2010

Comments