DevHow: Code Snippets from all around

Pagination with CodeIgniter Tutorial

Tag(s): PHP Codeigniter

This is supposedly a good template for generating pagination using CodeIgniter.

/*
* Controller
*
*/
// define the number of records per page
$per_page = 10;

// gets the total posts
$total = $this->posts_model->count_posts();

/*  gets posts with the limit and offset
Note: you should count where the offset in your URL should show
Example:
http://localhost/controller/method/10
$uri_segment = $this->uri->segment(3);

Example 2:
http://localhost/folder/controller/method/10
$uri_segment = $this->uri->segment(4);
*/
$uri_segment = $this->uri->segment(3);
$data['posts'] = $this->posts_model->get_posts($per_page, $uri_segment);

// set the config variables for pagination
$config['base_url'] = site_url('posts/browse');

// number of records
$config['total_rows'] = $total;

// records per page
$config['per_page'] = $per_page;

// this should be the same as your offset uri segment
$config['uri_segment'] = '3';

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

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


/*
* Model
*
*/

// which and how many to return
function get_posts($limit = NULL, $offset = NULL)
{
    if ($limit)
    {
    	$this->db->limit($limit, $offset);
    }

    return $this->db->get('posts');
}


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

/*
* View
*
*/

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

Comments

You must be logged in to comment