Part of the EllisLab Network
   
1 of 3
1
Pagination automated
Posted: 27 July 2008 02:07 PM   [ Ignore ]  
Research Assistant
Avatar
RankRankRank
Total Posts:  492
Joined  01-07-2008

Hi there,

Here’s an extension for the pagination class.

It automatically calculates the base_url and uri_segment for the pagination class so you don’t have to set them manually in your controller.

Also, it automatically calculates the offset form the URI and stores it in $this->pagination->offset, which you can use as LIMIT parameter in your database calls.

All you need to do order to calculate these values is to use a distinctive string in your URI, in the segment preceding the offset. For instance: www.example.com/blog/overview/Page/12 (in which ‘Page’ would be the distinctive string).

It’s the first lib I post here, so bear with me please.

1. Create this file MY_Pagination.php in the applications/libraries/ folder:

<?php  if (!defined('BASEPATH')) exit('No direct script access allowed');

/**
 * @name MY_Pagination.php
 * @version 1.0
 * @author Joost van Veen www.accentinteractive.nl
 * @created: Sun Jul 27 16:27:26 GMT 2008 16:27:26
 *
 * Extends CI's pagination class (http://codeigniter.com/user_guide/libraries/pagination.html)
 * It sets some variables for configuration of the pagination class dynamically,
 * depending on the URI, so we don't have to substract the offset from the URI,
 * or set $config['base_url'] and $config['uri_segment'] manually in the controller
 *
 * Here is what is set by this extension class:
 * 1. $this->offset - the current offset
 * 2. $this->uri_segment - the URI segment to be used for pagination
 * 3. $this->base_url - the base url to be used for pagination
 * (where $this refers to the pagination class)
 *
 * The way this works is simple:
 * If there we use pagination, it must ALWAYS follow the following syntax and be
 * located at the END of the URI:
 * PAGINATION_SELECTOR/offset
 *
 * The PAGINATION_SELECTOR is a special string which we know will ONLY be in the
 * URI when paging is set. Let's say the PAGINATION_SELECTOR is 'Page' (since most
 * coders never use any capitals in the URI, most of the times any string with
 * a single capital character in it will suffice). 
 *
 * Example use (in controller):
 * // Initialize pagination
 * $config['total_rows'] = $this->db->count_all_results('my_table');
 * $config['per_page'] = 10; // You'd best set this in a config file, but hey
 * $this->pagination->initialize($config);
 * $this->data['pagination'] = $this->pagination->create_links();
 *
 * // Retrieve paginated results, using the dynamically determined offset
 * $this->db->limit($config['per_page'], $this->pagination->offset);
 * $query = $this->db->get('my_table');
 *
 */
class MY_Pagination extends CI_Pagination {

    
var $offset 0;
    var 
$pagination_selector 'Page';

    function 
MY_Pagination()
    
{
        parent
::CI_Pagination();
        
log_message('debug'"MY_Pagination Class Initialized");

        
$this->_set_pagination_offset();

    
}

    
/**
     * Set dynamic pagination variables in $CI->data['pagvars']
     *
     */
    
function _set_pagination_offset()
    
{

        
// Instantiate the CI super object so we have access to the uri class
        
$CI =& get_instance();

        
// Store pagination offset if it is set
        
if (strstr($CI->uri->uri_string(), $this->pagination_selector)) {

            
// Get the segment offset for the pagination selector
            
$segments $CI->uri->segment_array();

            
// Loop through segments to retrieve pagination offset
            
foreach ($segments as $key => $value{

                
// Find the pagination_selector and work from there
                
if ($value == $this->pagination_selector{

                    
// Store pagination offset
                    
$this->offset $CI->uri->segment($key 1);

                    
// Store pagination segment
                    
$this->uri_segment $key 1;

                    
// Set base url for paging. This only works if the
                    // pagination_selector and paging offset are AT THE END of
                    // the URI!
                    
$uri $CI->uri->uri_string();
                    
$pos strpos($uri$this->pagination_selector);
                    
$this->base_url $CI->config->item('base_url') . substr($uri0$pos strlen($this->pagination_selector));
                
}

            }

        }
        
else // Pagination selector was not found in URI string. So offset is 0
            
$this->offset 0;
            
$this->uri_segment 0;
            
$this->base_url $CI->config->item('base_url') . $CI->uri->uri_string() . '/' $this->pagination_selector;

        
}

    }

}
?> 

In your controller, you create pagination an retrieve records from the database as such:

// Load the pagination class if you haven't already done so
// This will also load our extension class MY_Pagination.php
if(!$this->pagination{
    $this
->load->library('pagination');
}

// Initialize pagination
$config['total_rows'$this->db->count_all_results('my_table'); // count all records
$config['per_page'10// You'd best set rows per page in a config file, but hey
$this->pagination->initialize($config); // initialize pagination

// Create pagination links
$data['pagination_links'$this->pagination->create_links();
 
// Retrieve paginated results, using the dynamically determined offset
$this->db->limit($config['per_page']$this->pagination->offset);
$query $this->db->get('my_table');

if (
$query->num_rows() > 0{
   $data[
'results'$query->result();
}

// Load your view
$this->load->view('my_view'$data); 

Then, in your view you can use $pagination_links to display your pagination links.

Hope you enjoy this little lib.

 Signature 

http://codeigniter.tv/ - Codeigniter video tutorials
Create multiple aspect ratio thumbails library
Video tutorial series on MY_Model

Profile
 
 
Posted: 27 July 2008 02:13 PM   [ Ignore ]   [ # 1 ]  
Lab Assistant
Avatar
RankRank
Total Posts:  119
Joined  03-21-2008

Cool stuff!

Profile
 
 
Posted: 27 July 2008 02:39 PM   [ Ignore ]   [ # 2 ]  
Research Assistant
Avatar
RankRankRank
Total Posts:  492
Joined  01-07-2008

thanks smile

 Signature 

http://codeigniter.tv/ - Codeigniter video tutorials
Create multiple aspect ratio thumbails library
Video tutorial series on MY_Model

Profile
 
 
Posted: 31 August 2008 09:40 PM   [ Ignore ]   [ # 3 ]  
Summer Student
Total Posts:  1
Joined  08-31-2008

Useful lib,thanks for your share. LOL

Profile
 
 
Posted: 01 September 2008 02:19 AM   [ Ignore ]   [ # 4 ]  
Research Assistant
Avatar
RankRankRank
Total Posts:  801
Joined  04-20-2006

I like this extension, cool stuff!
You should add it the the wiki

 Signature 

Un blog seo white-hat expliquant quelques techniques intéressantes sur le seo black hat

Ionize CMS - Webdesigner CMS based on CodeIgniter
www.ionizecms.com

My website: Webagency Too Pixel

Profile
 
 
Posted: 07 October 2008 07:36 AM   [ Ignore ]   [ # 5 ]  
Summer Student
Avatar
Total Posts:  11
Joined  09-20-2008

I get a “page not found” when using the pagination links with my default “archives” controller / index view.

This works:

http://beta.archiv.local/archives/index/offset/5 

These don’t work:

http://beta.archiv.local/offset/5
http://beta.archiv.local/archives/offset/5 
Profile
 
 
Posted: 21 December 2008 09:05 AM   [ Ignore ]   [ # 6 ]  
Research Assistant
Avatar
RankRankRank
Total Posts:  492
Joined  01-07-2008

Hi wdm, sorry, didn’t see you post before.

You’re right, the paging identifier and offset can go anywhere in the URI except for the first two segments. This is because that’s where CI expects the controller and action to be.

In your case, CI thinks you want to call function 5 in controller offset.

 Signature 

http://codeigniter.tv/ - Codeigniter video tutorials
Create multiple aspect ratio thumbails library
Video tutorial series on MY_Model

Profile
 
 
Posted: 03 January 2009 10:42 PM   [ Ignore ]   [ # 7 ]  
Grad Student
Rank
Total Posts:  42
Joined  11-05-2007

Good solution, works great! Thank you smile

Profile
 
 
Posted: 30 May 2009 12:17 PM   [ Ignore ]   [ # 8 ]  
Summer Student
Total Posts:  13
Joined  12-18-2008

Hi

I am using your lib. and do the same as you mentioned above.
but I am not getting the exact and expected result.

i am using GET method here..  and query string is like..

[
http
://abc.com/index.php/search/do_search?keywords=&search_type=all&search_in=Entire_Resume&MinYear;=&MinCurrentSalary;=&MaxCurrentSalary;=&City;[]=&Segment;=&Area;=
/code]

I am writing query in search form so my query starts with 
[code]
$query 
"select SQL_CALC_FOUND_ROWS * from tbl_users where 1=1 ";

after a long if else condition finally my query saves in $query variable and Before implementing limit I make a clone of this variable

$total_result_query 
$query;
$sql_total_query $this->db->query("Select FOUND_ROWS() as numObjects");
$rs $sql_total_query->result_array();
$numEvents $rs[0]['numObjects'];


$config['total_rows'$rs[0]['numObjects']// count all records
$config['per_page'10// You'd best set rows per page in a config file, but hey
$this->pagination->initialize($config); // initialize pagination


// Create pagination links
$data['pagination_links'$this->pagination->create_links();
        
// Retrieve paginated results, using the dynamically determined offset
$this->db->limit($config['per_page']$this->pagination->offset);
        
//}


$sql $this->db->query($query); 

My problem is, query not including limit at the end.


please Guide me as it’s very urgent and i am new in this.

Profile
 
 
Posted: 30 May 2009 12:29 PM   [ Ignore ]   [ # 9 ]  
Summer Student
Total Posts:  13
Joined  12-18-2008
$total_result_query $query;
        
$sql_total_query $this->db->query("Select FOUND_ROWS() as numObjects");
        
$rs $sql_total_query->result_array();
        
//$numEvents = $rs[0]['numObjects'];

        // Initialize pagination
        
$config['total_rows'$rs[0]['numObjects']// count all records
        
$config['per_page'10// You'd best set rows per page in a config file, but hey
        
$this->pagination->initialize($config); // initialize pagination
        
        // Create pagination links
        
$data['pagination_links'$this->pagination->create_links();
        
        
// Retrieve paginated results, using the dynamically determined offset
        
$this->db->limit($config['per_page']$this->pagination->offset);
        
//}
        
$query.= " Limit ".$this->pagination->offset.",".$config['per_page'];

        echo 
$query;
        
//echo $config['per_page']."::::::::::".$this->pagination->offset;
        
$sql $this->db->query($query); 

when i add limit in my query.it’s working but now no paging links comes.

Profile
 
 
Posted: 01 June 2009 09:43 AM   [ Ignore ]   [ # 10 ]  
Research Assistant
Avatar
RankRankRank
Total Posts:  492
Joined  01-07-2008

Hi Dine,

First off, this lib is intended for use with default CI URI’s, that is: not including a query string (like ?keywords=&search_type=all), so you should expect to find some problems there.

Having said that, I think the problem here is that you switch between manual sql and active record in your queries. I’m not sure if that is at all possible. I think not. This is probably why limit is not in your query.

$query "select SQL_CALC_FOUND_ROWS * from tbl_users where 1=1 ";
// (...)
$this->db->limit($config['per_page']$this->pagination->offset);
$sql $this->db->query($query); 

Try to write the entire query in active record format, for instance

// Set up SQL
$this->db->where("(name LIKE '%mike%' OR address LIKE '%mike%')");
$this->db->limit($config['per_page']$this->pagination->offset);
$query $this->db->get('tbl_users');
// Fetch results
$result $query->num_rows() > query->result_array() : array(); 
 Signature 

http://codeigniter.tv/ - Codeigniter video tutorials
Create multiple aspect ratio thumbails library
Video tutorial series on MY_Model

Profile
 
 
   
1 of 3
1