Hello (it's my first post) I post because i really need help for paginate the results by category on codeigniter.
When i click on the link generated, the page loads to infinity. This pagination is ok on the index page for all results. But i need paginate by category.
thank you very very much in advance for you're help.
The Controler:
class Blog extends CI_Controller {
function __construct() {
parent::__construct();
$this->load->model(array('Blog_model'));
$this->load->library('Ajax_pagination');
$this->perPage = 3;
}
function category($category_id)//category page
{
$data = array();
//total rows count
$totalRec = count($this->Blog_model->getRowsByCat($category_id));
//pagination configuration
$config['target'] = '#postwrap';
$config['base_url'] = base_url().'blog/category/'.$category_id.'/ajaxPaginationCat';
$config['total_rows'] = $totalRec;
$config['per_page'] = $this->perPage;
$this->ajax_pagination->initialize($config);
//get the posts data
$data['posts'] = $this->Blog_model->getRowsByCat($category_id,array('limit'=>$this->perPage));
//
$data['main_content'] = "blog/category";
$this->load->view('template',$data);
}
function ajaxPaginationCat($category_id){
$page = $this->input->post('page');
if(!$page){
$offset = 0;
}else{
$offset = $page;
}
//total rows count
$totalRec = count($this->Blog_model->getRowsByCat($category_id));
//pagination configuration
$config['target'] = '#postwrap';
$config['base_url'] = base_url().'blog/category/'.$category_id.'/ajaxPaginationCat';
$config['total_rows'] = $totalRec;
$config['per_page'] = $this->perPage;
$this->ajax_pagination->initialize($config);
//get posts data
$data['posts'] = $this->Blog_model->getRowsByCat($category_id,array('start'=>$offset,'limit'=>$this->perPage));
//load the view
$this->load->view('blog/ajax-pagination-data', $data, false);
}
The Model:
/*
* get rows from the posts table
*/
function getRowsByCat($category_id,$params = array()){
$this->db->select('*');
$this->db->from('blog_posts');
$this->db->order_by('post_id','desc');
if(!empty($category_id)){
$this->db->where('category_id',$category_id);
}
//set start and limit
if(array_key_exists("start",$params) && array_key_exists("limit",$params)){
$this->db->limit($params['limit'],$params['start']);
}elseif(!array_key_exists("start",$params) && array_key_exists("limit",$params)){
$this->db->limit($params['limit']);
}
//get records
$query = $this->db->get();
//return fetched data
return ($query->num_rows() > 0)?$query->result_array():FALSE;
}
Library:
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
/**
* Pagination Class
*
* #package CodeIgniter
* #link http://codeigniter.com/user_guide/libraries/pagination.html
*
* Modified by CodexWorld.com
* #Ajax pagination functionality has added with this library.
* #It will helps to integrate Ajax pagination with loading image in CodeIgniter application.
* #TutorialLink http://www.codexworld.com/ajax-pagination-in-codeigniter-framework/
*/
class Ajax_pagination{
var $base_url = ''; // The page we are linking to
var $total_rows = ''; // Total number of items (database results)
var $per_page = 10; // Max number of items you want shown per page
var $num_links = 2; // Number of "digit" links to show before/after the currently viewed page
var $cur_page = 0; // The current page being viewed
var $first_link = 'First';
var $next_link = '»';
var $prev_link = '«';
var $last_link = 'Last';
var $uri_segment = 3;
var $full_tag_open = '<div class="pagination">';
var $full_tag_close = '</div>';
var $first_tag_open = '';
var $first_tag_close = ' ';
var $last_tag_open = ' ';
var $last_tag_close = '';
var $cur_tag_open = ' <b>';
var $cur_tag_close = '</b>';
var $next_tag_open = ' ';
var $next_tag_close = ' ';
var $prev_tag_open = ' ';
var $prev_tag_close = '';
var $num_tag_open = ' ';
var $num_tag_close = '';
var $target = '';
var $anchor_class = '';
var $show_count = true;
var $link_func = 'getData';
var $loading = '.loading';
/**
* Constructor
* #access public
* #param array initialization parameters
*/
function CI_Pagination($params = array()){
if (count($params) > 0){
$this->initialize($params);
}
log_message('debug', "Pagination Class Initialized");
}
/**
* Initialize Preferences
* #access public
* #param array initialization parameters
* #return void
*/
function initialize($params = array()){
if (count($params) > 0){
foreach ($params as $key => $val){
if (isset($this->$key)){
$this->$key = $val;
}
}
}
// Apply class tag using anchor_class variable, if set.
if ($this->anchor_class != ''){
$this->anchor_class = 'class="' . $this->anchor_class . '" ';
}
}
/**
* Generate the pagination links
* #access public
* #return string
*/
function create_links(){
// If our item count or per-page total is zero there is no need to continue.
if ($this->total_rows == 0 OR $this->per_page == 0){
return '';
}
// Calculate the total number of pages
$num_pages = ceil($this->total_rows / $this->per_page);
// Is there only one page? Hm... nothing more to do here then.
if ($num_pages == 1){
$info = 'Showing : ' . $this->total_rows;
return $info;
}
// Determine the current page number.
$CI =& get_instance();
if ($CI->uri->segment($this->uri_segment) != 0){
$this->cur_page = $CI->uri->segment($this->uri_segment);
// Prep the current page - no funny business!
$this->cur_page = (int) $this->cur_page;
}
$this->num_links = (int)$this->num_links;
if ($this->num_links < 1){
show_error('Your number of links must be a positive number.');
}
if ( ! is_numeric($this->cur_page)){
$this->cur_page = 0;
}
// Is the page number beyond the result range?
// If so we show the last page
if ($this->cur_page > $this->total_rows){
$this->cur_page = ($num_pages - 1) * $this->per_page;
}
$uri_page_number = $this->cur_page;
$this->cur_page = floor(($this->cur_page/$this->per_page) + 1);
// Calculate the start and end numbers. These determine
// which number to start and end the digit links with
$start = (($this->cur_page - $this->num_links) > 0) ? $this->cur_page - ($this->num_links - 1) : 1;
$end = (($this->cur_page + $this->num_links) < $num_pages) ? $this->cur_page + $this->num_links : $num_pages;
// Add a trailing slash to the base URL if needed
$this->base_url = rtrim($this->base_url, '/') .'/';
// And here we go...
$output = '';
// SHOWING LINKS
if ($this->show_count){
$curr_offset = $CI->uri->segment($this->uri_segment);
$info = 'Showing ' . ( $curr_offset + 1 ) . ' to ' ;
if( ( $curr_offset + $this->per_page ) < ( $this->total_rows -1 ) )
$info .= $curr_offset + $this->per_page;
else
$info .= $this->total_rows;
$info .= ' of ' . $this->total_rows . ' | ';
$output .= $info;
}
// Render the "First" link
if ($this->cur_page > $this->num_links){
$output .= $this->first_tag_open
. $this->getAJAXlink( '' , $this->first_link)
. $this->first_tag_close;
}
// Render the "previous" link
if ($this->cur_page != 1){
$i = $uri_page_number - $this->per_page;
if ($i == 0) $i = '';
$output .= $this->prev_tag_open
. $this->getAJAXlink( $i, $this->prev_link )
. $this->prev_tag_close;
}
// Write the digit links
for ($loop = $start -1; $loop <= $end; $loop++){
$i = ($loop * $this->per_page) - $this->per_page;
if ($i >= 0){
if ($this->cur_page == $loop){
$output .= $this->cur_tag_open.$loop.$this->cur_tag_close; // Current page
}else{
$n = ($i == 0) ? '' : $i;
$output .= $this->num_tag_open
. $this->getAJAXlink( $n, $loop )
. $this->num_tag_close;
}
}
}
// Render the "next" link
if ($this->cur_page < $num_pages){
$output .= $this->next_tag_open
. $this->getAJAXlink( $this->cur_page * $this->per_page , $this->next_link )
. $this->next_tag_close;
}
// Render the "Last" link
if (($this->cur_page + $this->num_links) < $num_pages){
$i = (($num_pages * $this->per_page) - $this->per_page);
$output .= $this->last_tag_open . $this->getAJAXlink( $i, $this->last_link ) . $this->last_tag_close;
}
// Kill double slashes. Note: Sometimes we can end up with a double slash
// in the penultimate link so we'll kill all double slashes.
$output = preg_replace("#([^:])//+#", "\\1/", $output);
// Add the wrapper HTML if exists
$output = $this->full_tag_open.$output.$this->full_tag_close;
?>
<script>
function getData(page){
$.ajax({
method: "POST",
url: "<?php echo $this->base_url; ?>"+page,
data: { page: page },
beforeSend: function(){
$('<?php echo $this->loading; ?>').show();
},
success: function(data){
$('<?php echo $this->loading; ?>').hide();
$('<?php echo $this->target; ?>').html(data);
}
});
}
</script>
<?php
return $output;
}
function getAJAXlink($count, $text) {
$pageCount = $count?$count:0;
return ''. $text .'';
}
}
// END Pagination Class
And the Ajax generated:
<script>
function getData(page){
$.ajax({
method: "POST",
url: "blog/category/1/ajaxPaginationCat/"+page,
data: { page: page },
beforeSend: function(){
$('.loading').show();
},
success: function(data){
$('.loading').hide();
$('#postwrap').html(data);
}
});
}
</script>
thank you so much!
Related
How can i customize my codeigniter links with bootstrap 4?
Im trying but i dont have luck with the a links.
thanks.
public function index($start=0)
{
if (!$this->session->userdata('user_id'))
{
redirect(base_url().'admin/login');
}
$this->load->model('M_Articulos');
$data['posts'] = $this->M_Articulos->select_posts(1, $start);
//paginacion
$this->load->library('pagination');
$config['base_url'] = base_url()."admin/index";
$config['total_rows'] = $this->M_Articulos->get_post_count();
$config['per_page'] = 1;
//paginacion estilos con bootstrap
$this->pagination->initialize($config);
$data['pages'] = $this->pagination->create_links(); //Links of pages
$this->load->view('admin/layouts/header');
$this->load->view('admin/modules/main', $data);
$this->load->view('admin/layouts/footer');
}
If you are using codeigniter-3,
check pagination library, if you are using default pagination library,
You need to make changes in create_links() function inside that as per your requirements.
Customizable code is here :
// Render the pages
if ($this->display_pages !== FALSE)
{
// Write the digit links
for ($loop = $start - 1; $loop <= $end; $loop++)
{
$i = ($this->use_page_numbers) ? $loop : ($loop * $this->per_page) - $this->per_page;
$attributes = sprintf('%s %s="%d"', $this->_attributes, $this->data_page_attr, $loop);
if ($i >= $base_page)
{
if ($this->cur_page === $loop)
{
// Current page
$output .= $this->cur_tag_open.$loop.$this->cur_tag_close;
}
elseif ($i === $base_page)
{
// First page
$output .= $this->num_tag_open.'<a href="'.$first_url.'"'.$attributes.$this->_attr_rel('start').'>'
.$loop.'</a>'.$this->num_tag_close;
}
else
{
$append = $this->prefix.$i.$this->suffix;
$output .= $this->num_tag_open.'<a href="'.$base_url.$append.'"'.$attributes.'>'
.$loop.'</a>'.$this->num_tag_close;
}
}
}
}
// Render the "next" link
if ($this->next_link !== FALSE && $this->cur_page < $num_pages)
{
$i = ($this->use_page_numbers) ? $this->cur_page + 1 : $this->cur_page * $this->per_page;
$attributes = sprintf('%s %s="%d"', $this->_attributes, $this->data_page_attr, $this->cur_page + 1);
$output .= $this->next_tag_open.'<a href="'.$base_url.$this->prefix.$i.$this->suffix.'"'.$attributes
.$this->_attr_rel('next').'>'.$this->next_link.'</a>'.$this->next_tag_close;
}
// Render the "Last" link
if ($this->last_link !== FALSE && ($this->cur_page + $this->num_links + ! $this->num_links) < $num_pages)
{
$i = ($this->use_page_numbers) ? $num_pages : ($num_pages * $this->per_page) - $this->per_page;
$attributes = sprintf('%s %s="%d"', $this->_attributes, $this->data_page_attr, $num_pages);
$output .= $this->last_tag_open.'<a href="'.$base_url.$this->prefix.$i.$this->suffix.'"'.$attributes.'>'
.$this->last_link.'</a>'.$this->last_tag_close;
}
public function paging($limit,$numRows,$page){
$allPages = ceil($numRows / $limit);
$start = ($page - 1) * $limit;
$querystring = "";
foreach ($_GET as $key => $value) {
if ($key != "page") $paginHTML .= "$key=$value&";
}
$paginHTML = "";
$paginHTML .= "Pages: ";
for ($i = 1; $i <= $allPages; $i++) {
$paginHTML .= "<a " . ($i == $page ? "class=\"selected\" " : "");
$paginHTML .= "href=\"?{$querystring}page=$i";
$paginHTML .= "\">$i</a> ";
}
return $paginHTML;
}
This is my pagination function for MVC pattern implementation.But this function has not displayed next and prev links.
I need to return HTML variable for pagination with previous and next link to controller.
I passed these variable to this function from controller.
$limit,$numRows,$page
How can I get next and prev links to above function.
I have added some conditions in the loop itself.
Hope they work.
Try the following:
<?php
public function paging($limit,$numRows,$page){
$allPages = ceil($numRows / $limit);
$start = ($page - 1) * $limit;
$querystring = "";
foreach ($_GET as $key => $value) {
if ($key != "page") $paginHTML .= "$key=$value&";
}
$paginHTML = "";
$paginHTML .= "Pages: ";
for ($i = 1; $i <= $allPages; $i++) {
if ($i>1) {
$prev = $i-1;
$paginHTML .= 'Previous';
}
$paginHTML .= "<a " . ($i == $page ? "class=\"selected\" " : "");
$paginHTML .= "href=\"?{$querystring}page=$i";
$paginHTML .= "\">$i</a> ";
if ($i<$allPages) {
$next = $i+1;
$paginHTML .= 'Next';
}
}
return $paginHTML;
}
?>
I'm using this pagination class like bellow inside my controller
case '' :
$page = isset ( $_REQUEST ['page'] ) ? $_REQUEST ['page'] : 1;
$limit = 5;
$allStudent = $student->getAllStudents();
$numRows = count($allStudent);
$start = ($page - 1) * $limit;
$students = $student->getStudentsWithLimit($start,$limit);
$paginHTML = $pagin->paging($limit,$numRows,$page);
$view->render('view/allStudent.php', array('allStudent' => $students,'pagin' => $paginHTML ));
break;
Get record function in Model class
public function getStudentsWithLimit($start,$limit){
$stmt = $this->db->con->query("SELECT * FROM student LIMIT $start, $limit");
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
return $results;
}
This should page with next and previous links with a max of 5 on either side of current page.
Pass in a function if you want the link formatted differently.
I've only given this very limited testing, and its been pulled out of a class, so you could replace some hard coded values in here with parameters of references to $this
function get_paging_links($result_count, callable $format_function=null)
{
if(!$format_function){
$format_function = function($url,$page,$qs){
$qs['page'] = $page;
return $url.'?'.http_build_query($qs);
};
}
$per_page = 5;
$total_pages = ceil($result_count / $per_page);
$return = [];
parse_str($_SERVER['QUERY_STRING'],$qs);
$url = $_SERVER['REQUEST_URI'];
//Remove existing query_string.
if($pos = strpos($url,'?')){
$url = substr($url,0,$pos);
}
$current_page = isset($qs['page']) ? $qs['page'] : 1;
$previous = $current_page -1;
if ($previous) {
$return['previous'] = $format_function($url,$previous,$qs);
}
for($i = max(1,$current_page-5); $i <= min($total_pages,$current_page+5); $i++) {
$return["$i"] = $format_function($url,$i,$qs);
}
$next_page = $current_page + 1;
if ($next_page < $total_pages){
$return['next'] = $format_function($url,$next_page,$qs);
}
return $return;
}
I got a strange problem, my current pagination link is not highlighted the pagination urls I made looks like:
site.com/list/50/?some=value
Everything is working great, but the current pagination link in view is not highlighted. I checked CSS and it's ok, the problem comes from the library I guess.
This is my code. I can't see anything wrong in here:
$pagination['base_url'] = site_url('asd');
if($_SERVER['QUERY_STRING'] !==''){
$pagination['suffix'] = '/?'.$_SERVER['QUERY_STRING'];
}
$pagination['first_url'] = site_url('asd');
$pagination['total_rows'] = $total_rows[0]->total;
$pagination['first_link'] = ' First ';
$pagination['last_link'] = ' Last ';
$pagination['next_link'] = ' Next ';
$pagination['prev_link'] = ' Prev ';
$pagination['num_links'] = 5;
$this->pagination->initialize($pagination);
Any clue appreciated.
i post my library which i edited for markup also:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
* CodeIgniter
*
* An open source application development framework for PHP 5.1.6 or newer
*
* #package CodeIgniter
* #author ExpressionEngine Dev Team
* #copyright Copyright (c) 2008 - 2011, EllisLab, Inc.
* #license http://codeigniter.com/user_guide/license.html
* #link http://codeigniter.com
* #since Version 1.0
* #filesource
*/
// ------------------------------------------------------------------------
/**
* Pagination Class
*
* #package CodeIgniter
* #subpackage Libraries
* #category Pagination
* #author ExpressionEngine Dev Team
* #link http://codeigniter.com/user_guide/libraries/pagination.html
*/
class CI_Pagination {
var $base_url = ''; // The page we are linking to
var $prefix = ''; // A custom prefix added to the path.
var $suffix = ''; // A custom suffix added to the path.
var $total_rows = ''; // Total number of items (database results)
var $per_page = 10; // Max number of items you want shown per page
var $num_links = 2; // Number of "digit" links to show before/after the currently viewed page
var $cur_page = 0; // The current page being viewed
var $first_link = '‹ First';
var $next_link = '>';
var $prev_link = '<';
var $last_link = 'Last ›';
var $uri_segment = 3;
var $full_tag_open = '<p class="CI-pagination">';
var $full_tag_close = '</p>';
var $first_tag_open = '<span class="pagination-first">';
var $first_tag_close = ' </span>';
var $last_tag_open = '<span class="pagination-last"> ';
var $last_tag_close = '</span>';
var $first_url = ''; // Alternative URL for the First Page.
var $cur_tag_open = '<span class="pagination-current"> <a href="javascript:void(0)" class="btn btn-small">';
var $cur_tag_close = '</a></span>';
var $next_tag_open = '<span class="pagination-next"> ';
var $next_tag_close = ' </span>';
var $prev_tag_open = '<span class="pagination-prev"> ';
var $prev_tag_close = '</span>';
var $num_tag_open = '<span class="pagination-num"> ';
var $num_tag_close = '</span>';
var $page_query_string = FALSE;
var $query_string_segment = 'per_page';
var $display_pages = TRUE;
var $anchor_class = 'btn btn-small';
/**
* Constructor
*
* #access public
* #param array initialization parameters
*/
public function __construct($params = array())
{
if (count($params) > 0)
{
$this->initialize($params);
}
if ($this->anchor_class != '')
{
$this->anchor_class = 'class="'.$this->anchor_class.'" ';
}
log_message('debug', "Pagination Class Initialized");
}
// --------------------------------------------------------------------
/**
* Initialize Preferences
*
* #access public
* #param array initialization parameters
* #return void
*/
function initialize($params = array())
{
if (count($params) > 0)
{
foreach ($params as $key => $val)
{
if (isset($this->$key))
{
$this->$key = $val;
}
}
}
}
// --------------------------------------------------------------------
/**
* Generate the pagination links
*
* #access public
* #return string
*/
function create_links()
{
// If our item count or per-page total is zero there is no need to continue.
if ($this->total_rows == 0 OR $this->per_page == 0)
{
return '';
}
// Calculate the total number of pages
$num_pages = ceil($this->total_rows / $this->per_page);
// Is there only one page? Hm... nothing more to do here then.
if ($num_pages == 1)
{
return '';
}
// Determine the current page number.
$CI =& get_instance();
if ($CI->config->item('enable_query_strings') === TRUE OR $this->page_query_string === TRUE)
{
if ($CI->input->get($this->query_string_segment) != 0)
{
$this->cur_page = $CI->input->get($this->query_string_segment);
// Prep the current page - no funny business!
$this->cur_page = (int) $this->cur_page;
}
}
else
{
if ($CI->uri->segment($this->uri_segment) != 0)
{
$this->cur_page = $CI->uri->segment($this->uri_segment);
// Prep the current page - no funny business!
$this->cur_page = (int) $this->cur_page;
}
}
$this->num_links = (int)$this->num_links;
if ($this->num_links < 1)
{
show_error('Your number of links must be a positive number.');
}
if ( ! is_numeric($this->cur_page))
{
$this->cur_page = 0;
}
// Is the page number beyond the result range?
// If so we show the last page
if ($this->cur_page > $this->total_rows)
{
$this->cur_page = ($num_pages - 1) * $this->per_page;
}
$uri_page_number = $this->cur_page;
$this->cur_page = floor(($this->cur_page/$this->per_page) + 1);
// Calculate the start and end numbers. These determine
// which number to start and end the digit links with
$start = (($this->cur_page - $this->num_links) > 0) ? $this->cur_page - ($this->num_links - 1) : 1;
$end = (($this->cur_page + $this->num_links) < $num_pages) ? $this->cur_page + $this->num_links : $num_pages;
// Is pagination being used over GET or POST? If get, add a per_page query
// string. If post, add a trailing slash to the base URL if needed
if ($CI->config->item('enable_query_strings') === TRUE OR $this->page_query_string === TRUE)
{
$this->base_url = rtrim($this->base_url).'&'.$this->query_string_segment.'=';
}
else
{
$this->base_url = rtrim($this->base_url, '/') .'/';
}
// And here we go...
$output = '';
// Render the "First" link
if ($this->first_link !== FALSE AND $this->cur_page > ($this->num_links + 1))
{
$first_url = ($this->first_url == '') ? $this->base_url : $this->first_url;
$output .= $this->first_tag_open.'<a '.$this->anchor_class.'href="'.$first_url.'">'.$this->first_link.'</a>'.$this->first_tag_close;
}
// Render the "previous" link
if ($this->prev_link !== FALSE AND $this->cur_page != 1)
{
$i = $uri_page_number - $this->per_page;
if ($i == 0 && $this->first_url != '')
{
$output .= $this->prev_tag_open.'<a '.$this->anchor_class.'href="'.$this->first_url.'">'.$this->prev_link.'</a>'.$this->prev_tag_close;
}
else
{
$i = ($i == 0) ? '' : $this->prefix.$i.$this->suffix;
$output .= $this->prev_tag_open.'<a '.$this->anchor_class.'href="'.$this->base_url.$i.'">'.$this->prev_link.'</a>'.$this->prev_tag_close;
}
}
// Render the pages
if ($this->display_pages !== FALSE)
{
// Write the digit links
for ($loop = $start -1; $loop <= $end; $loop++)
{
$i = ($loop * $this->per_page) - $this->per_page;
if ($i >= 0)
{
if ($this->cur_page == $loop)
{
$output .= $this->cur_tag_open.$loop.$this->cur_tag_close; // Current page
}
else
{
$n = ($i == 0) ? '' : $i;
if ($n == '' && $this->first_url != '')
{
$output .= $this->num_tag_open.'<a '.$this->anchor_class.'href="'.$this->first_url.'">'.$loop.'</a>'.$this->num_tag_close;
}
else
{
$n = ($n == '') ? '' : $this->prefix.$n.$this->suffix;
$output .= $this->num_tag_open.'<a '.$this->anchor_class.'href="'.$this->base_url.$n.'">'.$loop.'</a>'.$this->num_tag_close;
}
}
}
}
}
// Render the "next" link
if ($this->next_link !== FALSE AND $this->cur_page < $num_pages)
{
$output .= $this->next_tag_open.'<a '.$this->anchor_class.'href="'.$this->base_url.$this->prefix.($this->cur_page * $this->per_page).$this->suffix.'">'.$this->next_link.'</a>'.$this->next_tag_close;
}
// Render the "Last" link
if ($this->last_link !== FALSE AND ($this->cur_page + $this->num_links) < $num_pages)
{
$i = (($num_pages * $this->per_page) - $this->per_page);
$output .= $this->last_tag_open.'<a '.$this->anchor_class.'href="'.$this->base_url.$this->prefix.$i.$this->suffix.'">'.$this->last_link.'</a>'.$this->last_tag_close;
}
// Kill double slashes. Note: Sometimes we can end up with a double slash
// in the penultimate link so we'll kill all double slashes.
$output = preg_replace("#([^:])//+#", "\\1/", $output);
// Add the wrapper HTML if exists
$output = $this->full_tag_open.$output.$this->full_tag_close;
return $output;
}
}
// END Pagination Class
/* End of file Pagination.php */
/* Location: ./system/libraries/Pagination.php */
According to my pagination library, all my pagination links are printed out as class="pagination-num" and the class="pagination-current" is added only to the first pagination link , unbelievable :/
When changing page, the pagination looks always as shown in this image, no changes between a page to another :/
Read this and find the "Customizing the "Current Page" Link" section. Use that to add custom markup then add appropriate CSS.
Edit: the OP found the following solution:
$pagination['uri_segment'] = 2;
Add these line and write css for .current class
$pagination['cur_tag_open'] = '<a href="javascript:void(0)" class="current">';
$pagination['cur_tag_close'] = '</a>';
$pagination['cur_page'] = {put current page no here};
Check your $config['uri_segment']. Otherwise handle from jquery. Do somethings like:-
Suppose your link:-
<div id="my-ci-link"><?php echo $links; ?></div>
write jQuery:-
$('#my-ci-link strong').css('color','green');
<pre>
if ($this->uri->segment(2))
$data['page'] = $this->uri->segment(2);
else
$data['page'] = 0;
$config["cur_page"] = $data['page'];
...
</pre>
the problem with the class is that if i want to display 30 records at a time and i have 60 total records the pagination divs that shows the page numbers only shows page #1 and not page #2. i have tried to figure out how to fix it but i have given up. any help would greatly be apreciated.
this is how i call attributes to the class.
$paginate = new Pagination;
$paginate->pageName = "index.php"; //sets the page to use
$paginate->perPage = 10; //show num of records per page
$paginate->adjacents = 3; //current page adjacent to
$paginate->sql = "select * from tbl_products"; //the main query
$query = $db->query($paginate->getData());
while($row = mysql_fetch_object($query)) {
print $row->pName."<br/>";
}
$paginate->showPagination(); //shows the pagination div
here is the class.
<?php
include_once("class.db.php");
class Pagination
{
var $param;
var $perPage;
var $adjacents;
var $start;
var $sql;
var $pageName;
function __construct()
{
$this->db = new MysqlDB;
$this->db->connect();
}
function setParam()
{
if(isset($_GET['page']) && is_numeric($_GET['page']) && ($_GET['page'] > 0))
{
$this->param = $_GET['page'];
}
else
{
$this->param = 1;
}
}
function setIndex()
{
$this->setParam();
return $this->start = ($this->param * $this->perPage) - $this->perPage;
}
function showPagination($param1=null,$param2=null,$param3=null)
{
$qRows = $this->db->query($this->sql);
$numRows = $this->db->num_rows($qRows);
$numOfPages = ceil($numRows / $this->perPage);
$param = $this->param;
$pageName = $this->pageName;
$string = "";
//set pagination parameters.
if($param1 != null)
{
if(isset($_GET[$param1]))
{
$param1Value = $_GET[$param1];
$string .= "&".$param1."=".$param1Value;
}
}
if($param2 != null)
{
if(isset($_GET[$param2]))
{
$param2Value = $_GET[$param2];
$string .= "&".$param2."=".$param2Value;
}
}
if($param3 != null)
{
if(isset($_GET[$param3]))
{
$param3Value = $_GET[$param3];
$string .= "&".$param3."=".$param3Value;
}
}
print "<div class='pagination'>";
print "<a href='$this->pageName?page=1$string' class='previous-off'> First </a>";
// ----------------------------------------------------------------------------
// PRINT ALL PAGES TO THE LEFT //
if(($param - $this->adjacents) > 1)
{
print "<span>...</span>";
$lowerLimit = $param - $this->adjacents;
//print all on left side.
for($i = $lowerLimit; $i< $param; $i++)
{
print "<a href='$pageName?page=$param = $i$string'> $i </a>";
}
}
else
{
//print all numbers between current page and first page.
for($i = 1; $i < $param; $i++)
{
print "<a href='$pageName?page=$i$string'> $i </a>";
}
}
// ----------------------------------------------------------------------------
//print current page
if(($param != 0) && ($param != $numOfPages))
{
print "<span class='current'>$param</span>";
}
// ----------------------------------------------------------------------------
//PRINT ALL PAGES TO THE RIGHT
if(($param + $this->adjacents) < $numOfPages)
{
$upperLimit = $param + $this->adjacents;
for($i=($param + 1); $i<=$upperLimit; $i++)
{
print "<a href='$pageName?page=$i$string'> $i </a>";
}
print "<span>...</span>";
}
else
{
//print all page numbers if out of padded range
for($i = ($param + 1); $i<$numOfPages; $i++ )
{
print "<a href='$pageName?page=$i$string'> $i </a>";
}
}
// ----------------------------------------------------------------------------
$lastPage = $numOfPages - 1;
print "<a class='next' href='$pageName?page=$lastPage$string'> Last </li>";
print "</div>";
}
function getData()
{
$query = $this->sql;
$this->start = $this->setIndex();
return "$query LIMIT $this->start, $this->perPage";
}
function errors()
{
$query = $this->sql;
print "$query LIMIT $this->start, $this->perPage"."<br/>";
print "this->start ".$this->start."<br/>";
print "this->param ".$this->param."<br/>";
print "this->perPage ".$this->perPage."<br/>";
print "this->setindex() ".$this->setIndex()."<br/>";
}
}
?>
Personally I tend to stray from SELECT * FROM tbl type queries as if you have a large table, it can be slow. Therefore, I run two queries: one to get the total number of records, and one to get the data set I need based on a paging parameter in the URL, e.g. example.com/news.php?page=2.
From there, I can instantiate my own paging class, which is pretty simple:
<?php
class Paging {
private $total;
private $batch;
private $page;
private $prefix;
public function __construct($total=0, $batch=10, $page=1, $url="") {
$this->total = intval($total);
$this->batch = intval($batch);
$this->page = intval($page);
$this->url = $url;
}
public function total_pages() {
return ceil($this->total/$this->batch);
}
public function render() {
$html = "";
// only display paging if we have more than the batch value
if ($this->total > $this->batch) {
$html.= '<p>Go to page:';
for ($i=1; $i <= $this->total_pages()) {
if ($i==$this->page) {
$html.= ' <span class="current">'.$i.'</span>';
}
else {
$html.= ' '.$i.'';
}
}
$html.= '</p>';
}
return $html;
}
}
Then to use:
<?php
// get total number of records
$sql = "SELECT COUNT(*) AS total FROM tbl";
$res = $db->query($sql);
$row = $res->fetch();
$total = $row['total'];
$batch = 20;
$page = intval($_GET['page']);
// instantiate paging class
require_once('paging.class.php');
$paging = new Paging($total, $batch, $page, "mypage.php?page=%s");
// do normal page stuff here...
// render the pagination links
echo $paging->render();
Feel free to use the above code and modify to your needs
ive written a pagination class and it looks like its not outputting the correct amount of rows. i have a table full of 51 records and instead it shows only 30 records and as for the pages it shows only page 1 where it should show page 1 and 2. the pages are viewed by going to page=1 as a browser param. when i try to view page=2 i see the rest of the records. here is the class.
include_once("class.db.php");
class Pagination {
var $param;
var $perPage;
var $adjacents;
var $start;
var $sql;
var $pageName;
function __construct() {
$this->db = new MysqlDB;
$this->db->connect();
}
function setParam() {
if(isset($_GET['page']) && is_numeric($_GET['page']) && ($_GET['page'] > 0)) {
$this->param = $_GET['page'];
} else {
$this->param = 1;
}
}
function setIndex() {
$this->setParam();
return $this->start = ($this->param * $this->perPage) - $this->perPage;
}
function showPagination() {
$qRows = $this->db->query($this->sql);
$numRows = $this->db->num_rows($qRows);
$numOfPages = ceil($numRows / $this->perPage);
$param = $this->param;
$pageName = $this->pageName;
print "<div class='pagination'>";
print "<a href='$this->pageName?page=1' class='previous-off'> First </a>";
// ----------------------------------------------------------------------------
// PRINT ALL PAGES TO THE LEFT //
if(($param - $this->adjacents) > 1) {
print "<span>...</span>";
$lowerLimit = $param - $this->adjacents;
//print all on left side.
for($i = $lowerLimit; $i< $param; $i++) {
print "<a href='$pageName?page=$param = $i'> $i </a>";
}
} else {
//print all numbers between current page and first page.
for($i = 1; $i < $param; $i++) {
print "<a href='$pageName?page=$i'> $i </a>";
}
}
// ----------------------------------------------------------------------------
//print current page
if(($param != 0) && ($param != $numOfPages)) {
print "<span class='current'>$param</span>";
}
// ----------------------------------------------------------------------------
//PRINT ALL PAGES TO THE RIGHT
if(($param + $this->adjacents) < $numOfPages) {
$upperLimit = $param + $this->adjacents;
for($i=($param + 1); $i<=$upperLimit; $i++) {
print "<a href='$pageName?page=$i'> $i </a>";
}
print "<span>...</span>";
} else {
//print all page numbers if out of padded range
for($i = $param + 1; $i<$numOfPages; $i++ ) {
print "<a href='$pageName?page=$i'> $i </a>";
}
}
// ----------------------------------------------------------------------------
$lastPage = $numOfPages - 1;
print "<a class='next' href='$pageName?page=$lastPage'> Last </li>";
print "</div>";
}
function getData() {
$query = $this->sql;
$this->start = $this->setIndex();
return "$query LIMIT $this->start, $this->perPage";
}
}
this is how i use the class:
$db = new MysqlDB;
$paginate = new Pagination;
$paginate->pageName = "index.php"; //sets the page to use
$paginate->perPage = 10; //show num of records per page
$paginate->adjacents = 3; //current page adjacent to
$paginate->sql = "select * from tbl_products"; //the main query
$query = $db->query($paginate->getData());
while($row = mysql_fetch_object($query)) {
print $row->pName."<br/>";
}
$paginate->showPagination(); //shows the pagination div
In function setIndex you have to write:
return $this->start = (($this->param - 1) * $this->perPage) - $this->perPage;
because a query should look like:
for page 1: SELECT ... LIMIT 0,[nr_of_pages]
for page 2: SELECT ... LIMIT [nr_of_pages]*1,[nr_of_pages]
...