Tuesday, July 14, 2009

Pagination in codeigniter

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.

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.


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.



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.

No comments:

Post a Comment