Skip to content

Instantly share code, notes, and snippets.

@joseadrian
Last active December 28, 2015 03:29
Show Gist options
  • Save joseadrian/7435689 to your computer and use it in GitHub Desktop.
Save joseadrian/7435689 to your computer and use it in GitHub Desktop.
Codeigniter paging. Methods to get info about total rows of they query using FOUND_ROWS(). ar_ prefix for versión >= 3 qb_ prefix for version < 3
<?php
/*
* Add this methos on the system/database/DB_active_rec.php file
*/
/**
*
* Method to stablish the limit and offset
*/
public function set_paging($page = 1, $results_per_page = 20)
{
$this->ar_page = ($page > 1) ? --$page : 0;
$this->ar_limit = $this->ar_results_per_page = (int) $results_per_page;
$this->ar_offset = (int) ($this->ar_page * $this->ar_results_per_page);
return $this;
}
/**
*
* Method to get paging info
*/
public function get_paging()
{
// Executing the last query again because all the info is reseted after executing the query
// ->query(...), ->get(...), ->get_where(...)
$this->simple_query(preg_replace('/SELECT/', 'SELECT SQL_CALC_FOUND_ROWS', $this->last_query(), 1));
// Getting the rows found
$total = $this->query('SELECT FOUND_ROWS() AS "total";')->row()->total;
$data = array(
// Total numbers of records of the last query executed
'total' => $total
// Total number of pages
, 'pages' => ceil($total / $this->ar_results_per_page)
// Beccause we don't want to have a zero page we add +1
, 'page' => ++$this->ar_page
);
// Reset the values
$this->ar_page = $this->ar_result_per_page = 0;
return $data;
}
<?php
function Pokemon_Model example CI_Model
{
function __construct()
{
parent::__construct();
$this->load->database();
}
function get_list($page = 1)
{
$results_per_page = 50;
$this->db->select('pokemon_type');
$this->db->group_by('pokemon_type');
$this->db->set_paging($page, $results_per_page);
$data['result'] = $this->db->get('pokemon')->result_array();
$data['paging'] = $this->db->get_paging();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment