how to configure pagination codeigniter? - php

Ive trying to make a pagination with CodeIgniter, it should be so simple according the manual of Codeigniter, even in the example is like this
« First < 1 2 3 4 5 > Last »
$config['total_rows'] = $this->searchdesc_model->queryallrows();
$config['per_page'] = '10';
$config['uri_segment'] =4;
$config['full_tag_open'] = '<p>';
$config['full_tag_close'] = '</p>';
$config['cur_tag_open'] = '<b>';
$config['cur_tag_close'] = '</b>';
$config['first_link'] = 'First';
$config['last_link'] = 'Last';
$config['last_tag_open'] = '<p>';
$config['last_tag_close'] = '</p>'
$this->load->library('Company_Creation');
in the view I only call it like this pagination->create_links(); ?> (or I send it through the view when I call it from the controller, still I only get this
1 2 3 >
and there is no way to make it look like the exmaple, may sound so dummy but , anyone could help me with this? or have a problem similar?
Thanks
EDIT 1
$config['total_rows'] = $this->searchdesc_model->queryallrows();
$config['per_page'] = '5';
$config['uri_segment'] =4;
$config['full_tag_open'] = '<p>';
$config['full_tag_close'] = '</p>';
$config['cur_tag_open'] = '<b>';
$config['cur_tag_close'] = '</b>';
$config['first_link'] = ' First';
$config['last_link'] = ' Last';
$config['last_tag_open'] = '<p>';
$config['last_tag_close'] = '</p>';
$config['next_link'] = '';
$config['next_tag_open'] = '<p id="nextbutton" style="padding-left:5px;">';
$config['next_tag_close'] = '</p>';
$config['prev_link'] = '';
$config['prev_tag_open'] = '<p id="prevbutton" style="padding-right:5px;">';
$config['prev_tag_close'] = '</p>';
$config['num_links']=4;
$data['retorno'] = $this->searchdesc_model->queryalldb($config['per_page'],$this->uri->segment(4,0));
$config['total_rows']=1000;
$this->pagination->initialize($config);
I did this according some advices Ive recieve, like you said when are many data it works good, still I'd LOVE to show first and next button all time, I set total_rows after my query (which I call with the right number of rows) , and I tried before too and the results are the same, I also need to show only 4 numbers and I am ustying numb_links ... still doesnt work (I dont know why Ci docs say should work..) any idea?
Thanks!

To produce what the example shows is actually pretty easy. You just need to extend the Pagination's Library to accommodate this. I was able to do this. No matter how many pages you show it still shows first, last, back arrow, and forward arrow.
If you are wanting to show 5 pages at all times with the foward and back stuff you need to have that many results to fill that page. Then you set num_links to what you would want before and after if on the 3rd page. So it would be 2. My changes if you are on the 1st page make it display 4 pages after when applicable. See image below. White is current page. Green is pages available.
Hopefully I've explained everything correctly and this works for you. Let me know.
Controller
$this->pagingConfig = array();
$this->pagingConfig['base_url'] = 'URL';
$this->pagingConfig['total_rows'] = 0;//TOTAL ROWS
$this->pagingConfig['cur_page'] = 0;//CURRENT PAGE NUMBER
$this->pagingConfig['per_page'] = 0;//YOUR RESULTS PER PAGE
$this->pagingConfig['num_links'] = 2;//NUMBER OF LINKS BEFORE AND AFTER CURRENT PAGE IF ON PAGE ONE WILL SHOW 4 PAGES AFTERWARDS IF YOU HAVE ENOUGH RESULTS TO FILL THAT MANY
$this->pagingConfig['first_link'] = "<< First";
$this->pagingConfig['last_link'] = "Last >>";
$this->pagingConfig['full_tag_open'] = "<div class='pagination'>";
$this->pagingConfig['full_tag_close'] = "</div>";
$this->pagingConfig['last_tag_open'] = "";
$this->pagingConfig['first_tag_close'] = "";
$this->pagingConfig['anchor_class'] = "page";
$this->pagination->initialize($this->pagingConfig);
$strPaging = $this->pagination->create_links();
EXTENDED PAGINATION LIBRARY CALL
function create_links()
{
// EDIT: ADDED THIS BECAUSE COULDN'T SEEM TO SET THIS ANYWHERE ELSE
if ($this->anchor_class != '')
{
$this->anchor_class = 'class="'.$this->anchor_class.'" ';
}
// 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 = 1;
}
// 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);
}
// EDIT: DON'T NEED THIS THE WAY I'VE CHANGED IT
// $uri_page_number = $this->cur_page;
// $this->cur_page = floor(($this->cur_page/$this->per_page) + 1);
// EDIT: START OF MODIFIED START AND END TO WORK HOW I WANT
$totalLinks = ($this->num_links*2)+1;
if($totalLinks > ($this->total_rows/$this->per_page))
{
$totalLinks = ceil($this->total_rows/$this->per_page);
}
//first page
if($this->cur_page == 1)
{
$start = 1;
$end = $start + $totalLinks - 1;
}
//middle pages
elseif($this->cur_page + $this->num_links <= $num_pages && $this->cur_page - $this->num_links > 0)
{
$start = $this->cur_page - $this->num_links;
$end = $this->cur_page + $this->num_links;
}
//last couple of pages
elseif(($this->cur_page + $totalLinks) > $num_pages)
{
$start = $num_pages - $totalLinks + 1;
$end = $num_pages;
//check to see if this is in the first half of links so it doesn't jump the paging
if($this->cur_page <= $this->num_links)
{
$start = 1;
$end = $start + $totalLinks - 1;
}
}
//first couple of pages
elseif(($this->cur_page - $totalLinks) < 1)
{
$start = 1;
$end = $start + $totalLinks - 1;
}
// EDIT: END OF MODIFIED START AND END TO WORK HOW I WANT
// EDIT: CODEIGNITERS BASE PAGING SETUP SEE ABOVE FOR MY CHANGES
// $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
// EDIT: CHANGED TO ALWAYS SHOW FIRST LINK AT LEAST
if ($this->first_link !== FALSE AND $this->cur_page != 1)
{
$first_url = ($this->first_url == '') ? $this->base_url."1" : $this->first_url;
$output .= $this->first_tag_open.'<a '.$this->anchor_class.'href="'.$first_url.'">'.$this->first_link.'</a>'.$this->first_tag_close;
}
else
{
$output .= $this->cur_tag_open.$this->first_link.$this->cur_tag_close;
}
// Render the "previous" link
// EDIT: CHANGED TO ALWAYS SHOW PREVIOUS LINK AT LEAST
if ($this->prev_link !== FALSE AND $this->cur_page != 1)
{
$i = $this->cur_page-1;
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;
}
}
else
{
$output .= $this->cur_tag_open.$this->prev_link.$this->cur_tag_close;
}
// EDIT: CHANGED THIS TO ALWAYS SHOW ALL LINKS WANTED EVEN IF ON FIRST PAGE
// Render the pages
if ($this->display_pages !== FALSE)
{
// Write the digit links
for ($loop = $start; $loop <= $end; $loop++)
{
// EDIT: DON'T NEED THIS THE WAY I'VE CHANGED IT
// $i = ($loop * $this->per_page) - $this->per_page;
if ($loop >= 0)
{
if ($this->cur_page == $loop)
{
$output .= $this->cur_tag_open.$loop.$this->cur_tag_close; // Current page
}
else
{
$n = ($loop == 0) ? '0' : $loop;
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
// EDIT: CHANGED TO ALWAYS SHOW NEXT LINK AT LEAST
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+1).$this->suffix.'">'.$this->next_link.'</a>'.$this->next_tag_close;
}
else
{
$output .= $this->cur_tag_open.$this->next_link.$this->cur_tag_close;
}
// Render the "Last" link
// EDIT: CHANGED TO ALWAYS SHOW LAST LINK AT LEAST
if ($this->last_link !== FALSE AND $this->cur_page != $num_pages)
{
$i = (($num_pages));
$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;
}
else
{
$output .= $this->cur_tag_open.$this->last_link.$this->cur_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;
}

The only reason you get 1 2 3 > instead of « First < 1 2 3 4 5 > Last » is that you simply don't have enough rows in your result to generate more than 3 pages.
The "First" and "Last" links don't appear by default if you don't need them. It's not very clear from the documentation's example.
You won't get "Previous" links until you advance past page 1, the example is actually on page 3 (the "3" is bold).
Since you're providing your own templates in the configuration instead of using the defaults, your actual results will be slightly different.
If you want to do a quick test to see more links, just reduce your per_page to a lower number or include more rows in your total_rows. The total number of links shown can also be configured with num_links.

For those people who developing their CI app with PostgreSql and can't understand why pagination limit+offset works "weird":
Controller:
...
$offset = ($page-1)*$config["per_page"];
$this->reporting_model->some_fetch_method($id, $config["per_page"], $offset);
...
Model:
...
$this->db->limit($limit_perpage, $offset);
$this->db->where("id", $id);
$this->db->get('some_table');
...

Related

codeigniter 3 customize pagination bootstrap

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;
}

Pagination current link not highlighting

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>

Pagination system always missing 1 result

I have a pagination system, that fetches all of the results from a database & then loads them into a pagination.
Let's say I set the limit to 5 results per page, it will generate more pages, and order the results by date & time.
But I have a problem, my system always missing the most new result (by date/time) in the database, I have no idea why..
This is the code:
// how many rows to show per page
$rowsPerPage = 10;
// by default we show first page
$page_num = 1;
// if $_GET['page'] defined, use it as page number, $_GET gets the page number out of the url
//set by the $page_pagination below
if(isset($_GET['page'])){$page_num = $_GET['page'];}
//the point to start for the limit query
$offset = $page_num;
// Zero is an incorrect page, so switch the zero with 1, mainly because it will cause an error with the SQL
if($page_num == 0) {$page_num = 1;}
// counting the offset
$sql = "SELECT * FROM comments ORDER BY date, time desc LIMIT $offset, $rowsPerPage";
$res = $pdo->query($sql);
// how many rows we have in database
$sql2 = "SELECT COUNT(comment_id) AS numrows FROM comments";
$res2 = $pdo->query($sql2);
$row2 = $res2->fetch();
$numrows = $row2['numrows'];
// print the random numbers
while($row = $res->fetch())
{
//Echo out your table contents here.
echo $row[1].'<BR>';
echo $row[2].'<BR>';
echo '<BR>';
}
// how many pages we have when using paging?
$numofpages = ceil($numrows/$rowsPerPage);
// print the link to access each page
$self = "events.php?";
$page_pagination = '';
if ($numofpages > '1' ) {
$range = 10; //set this to what ever range you want to show in the pagination link
$range_min = ($range % 2 == 0) ? ($range / 2) - 1 : ($range - 1) / 2;
$range_max = ($range % 2 == 0) ? $range_min + 1 : $range_min;
$page_min = $page_num- $range_min;
$page_max = $page_num+ $range_max;
$page_min = ($page_min < 1) ? 1 : $page_min;
$page_max = ($page_max < ($page_min + $range - 1)) ? $page_min + $range - 1 : $page_max;
if ($page_max > $numofpages) {
$page_min = ($page_min > 1) ? $numofpages - $range + 1 : 1;
$page_max = $numofpages;
}
$page_min = ($page_min < 1) ? 1 : $page_min;
if ( ($page_num > ($range - $range_min)) && ($numofpages > $range) ) {
$page_pagination .= '<a class="num" title="First" href="'.$self.'page=1"><</a> ';
}
if ($page_num != 1) {
$page_pagination .= '<a class="num" href="'.$self.'page='.($page_num-1). '">Previous</a> ';
}
for ($i = $page_min;$i <= $page_max;$i++) {
if ($i == $page_num)
$page_pagination .= '<span class="num"><strong>' . $i . '</strong></span> ';
else
$page_pagination.= '<a class="num" href="'.$self.'page='.$i. '">'.$i.'</a> ';
}
if ($page_num < $numofpages) {
$page_pagination.= ' <a class="num" href="'.$self.'page='.($page_num + 1) . '">Next</a>';
}
if (($page_num< ($numofpages - $range_max)) && ($numofpages > $range)) {
$page_pagination .= ' <a class="num" title="Last" href="'.$self.'page='.$numofpages. '">></a> ';
}
}
echo $page_pagination.'<BR><BR>';
echo 'Number of results - '.$numrows ;
echo ' and Number of pages - '.$numofpages.'<BR><BR>';
$res2->closeCursor();
Question:
What have I done wrong? I cant' really see anything wrong, but I always get this error:
Notice: Undefined variable: page_pagination
Line:
echo $page_pagination.'<BR><BR>';
It always happens on a different line, depends on the results amount, but to fix that I need to declare page_pagination = ''; before the whole thing.
How can I fix this and what is causing this problem?
Thanks.
Your $offset is being set to 1. The newest one is always missing because it's going form 1-10 rather than 0-9. Index starts at 0. The following should work.
$offset = ($rowsPerPage * $page_num) - $rowsPerPage;

Pagination do not correct display page numbers Codeigniter

My controller function
function test($start_from = 0)
{
$this->load->library('pagination');
$data = array();
$per_page = 3;
$total = $this->activity_model->count_by();
$config['base_url'] = base_url() . 'test';
$config['total_rows'] = $total;
$config['per_page'] = $per_page;
$config['uri_segment'] = 2;
$config['num_links'] = 2;
$config['use_page_numbers'] = TRUE;
$data['follow'] = $this->activity_model->get($per_page, $start_from);
$this->pagination->initialize($config);
$data['pagination'] = $this->pagination->create_links();
$this->load->view('front_end/test' ,$data);
}
my route :
$route['test'] = "user_activity/test";
$route['test/(:any)'] = "user_activity/test/$1";
model :
function get($limit,$start_from)
{
$sql = "SELECT * FROM user_follow LIMIT $start_from, $limit";
$query = $this->db->query($sql);
return $query->result_array();
}
Problem is that I have pagination 1,2,3,4,5.... and in every page I display 3 items. I want to do that in url it show my page numbers 1,2,3,4,5
When I click second page url show 3
When I click third page url show 6 and so on +3
is it possible, I spend hours for looking advice on internet but nothing as I understand [code]$config['use_page_numbers'] = TRUE;[/code] do what I need but in my case it still do not work.
Maybe you can advice any library ?
I managed to do this without modifying the class. The best way will be to make a copy of the pagination class, make your changes and use it. This way if you update CI, you won't lose the modification. Here is my solution without modifying the class.
First I want to say that using only the config option $config['use_page_numbers'] = TRUE will also do the trick but not entirely. The things I found out not working using only this option are the following:
if you try to edit the url bar pages manually it treats them like offset not like pages and also if you try to go back from page 2 to page 1 using the "prev" link it also treats the page number like an an offset.
The code:
$config['base_url'] = base_url('my/url/page');
$config['total_rows'] = count($this->my_model->get_all());
$config['per_page'] = 2;
$config['use_page_numbers'] = TRUE;
$config['uri_segment'] = 4;
//i'm looading the pagination in the constuctor so just init here
$this->pagination->initialize($config);
if($this->uri->segment(4) > 0)
$offset = ($this->uri->segment(4) + 0)*$config['per_page'] - $config['per_page'];
else
$offset = $this->uri->segment(4);
//you should modify the method in the model to accept limit and offset or make another function - your choice
$data['my_data'] = $this->my_model->get_all($config['per_page'], $offset);
This way
page = false (my/url) or (my/url/page) - basically if the 4th uri segment is false,
page = 0 (my/url/page/0),
and
page = 1 (my/url/page/1)
will all display the first page and then the other links will be working fine. I'm also validating the page e.g - if someone wants to enter (my/url/page/2323) this will throw an error and in the model you should check if the result is false and if it is the controller should show an error page or something. Hope this helps.
Make the following changes in Pagination class (/system/libraries/Pagination.php) so that it uses page numbers instead of offsets.
OLD (lines 146–153):
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;
}
NEW:
Add ‘else’ option to if-statement to make sure default is; page = 1.
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;
}
else
{
$this->cur_page = 1;
}
OLD (line 175):
$this->cur_page = floor(($this->cur_page/$this->per_page) + 1);
NEW:
Simply comment out this line so current page obeys controller/URI.
//$this->cur_page = floor(($this->cur_page/$this->per_page) + 1);
OLD (line 206):
$i = $uri_page_number - $this->per_page;
NEW:
Previous page should always be current page subtracted by 1.
$i = $uri_page_number - 1;
OLD (line 230):
if ($this->cur_page == $loop)
NEW:
URIs missing pagination should be considered page 1.
if ($this->cur_page == $loop || ($this->cur_page == 1 && $this->cur_page == $loop))
OLD (line 238–247):
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;
}
NEW:
Page URLs should use page numbers and not offsets.
if ($n == '' && $this->first_url != '')
{
$output .= $this->num_tag_open.'<a '.$this->anchor_class.'href="'.$loop.'">'.$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.$loop.'">'.$loop.'</a>'.$this->num_tag_close;
}
OLD (line 256):
$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;
NEW:
Next page should always be the sum of current page and 1.
$output .= $this->next_tag_open.'<a '.$this->anchor_class.'href="'.$this->base_url.$this->prefix.($this->cur_page + 1).$this->suffix.'">'.$this->next_link.'</a>'.$this->next_tag_close;
OLD (line 262):
$i = (($num_pages * $this->per_page) - $this->per_page);
NEW:
Last page should be the total number of pages.
$i = $num_pages;
Replace all the old lines with new lines. Make sure you do a backup of file before changing.
Hope this helps :)
EDIT:
You need to update your controller function test like :
function test($start_from = 0)
{
$this->load->library('pagination');
$data = array();
$per_page = 3;
$total = $this->activity_model->count_by();
$config['base_url'] = base_url() . 'test';
$config['total_rows'] = $total;
$config['per_page'] = $per_page;
$config['uri_segment'] = 2;
$config['num_links'] = 2;
$config['use_page_numbers'] = TRUE;
$start = $per_page * ($start_from-1);
$data['follow'] = $this->activity_model->get($per_page, $start);
$this->pagination->initialize($config);
$data['pagination'] = $this->pagination->create_links();
$this->load->view('front_end/test' ,$data);
}
Here i have added a new variable $start which is $per_page * ($start_from-1). Now pass this $start as argument to model.
What this do is multiply the number of items per page with (current page number -1 ) .This means if your items per page is 10 and you are on the second page the $start = 10 *(2-1) which gives 10. So your result will start from 10,20 and so one
Hope this helps :)
You can avoid php errors if someone manually entering the page number from the URL:
for example my/url/page/786
your result might not have anything to display for the query 786 , by default it will show you php error..to avoid this you can use:
if (isset($result)) {
$isArray = is_array($result) ? "YES" : "NO"; //check that result is an array or not as per your requirement.
if ($isArray == "YES") {
echo "show your stuffs here..";
}
else{
echo "display your message instead for php error here..";
}
}
hope this helps...
for query tweet me at twitter #sufiyantech

paging query problem

here is my paging code:
function getPagingQuery($sql, $itemPerPage = 10)
{
if (isset($_GET['page']) && (int)$_GET['page'] > 0) {
$page = (int)$_GET['page'];
} else {
$page = 1;
}
// start fetching from this row number
$offset = ($page - 1) * $itemPerPage;
return $sql . " LIMIT $offset, $itemPerPage";
}
function getPagingLink($sql, $itemPerPage = 10, $strGet ="")
{
$result = dbQuery($sql);
$pagingLink = '';
$totalResults = dbNumRows($result);
$totalPages = ceil($totalResults / $itemPerPage);
// how many link pages to show
$numLinks = 10;
// create the paging links only if we have more than one page of results
if ($totalPages > 1) {
$self = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'] ;
if (isset($_GET['page']) && (int)$_GET['page'] > 0) {
$pageNumber = (int)$_GET['page'];
} else {
$pageNumber = 1;
}
// print 'previous' link only if we're not
// on page one
if ($pageNumber > 1) {
$page = $pageNumber - 1;
if ($page > 1) {
$prev = " [Prev] ";
} else {
$prev = " [Prev] ";
}
$first = " [First] ";
} else {
$prev = ''; // we're on page one, don't show 'previous' link
$first = ''; // nor 'first page' link
}
// print 'next' link only if we're not
// on the last page
if ($pageNumber < $totalPages) {
$page = $pageNumber + 1;
$next = " [Next] ";
$last = " [Last] ";
} else {
$next = ''; // we're on the last page, don't show 'next' link
$last = ''; // nor 'last page' link
}
$start = $pageNumber - ($pageNumber % $numLinks) + 1;
$end = $start + $numLinks - 1;
$end = min($totalPages, $end);
$pagingLink = array();
for($page = $start; $page <= $end; $page++) {
if ($page == $pageNumber) {
$pagingLink[] = " $page "; // no need to create a link to current page
} else {
if ($page == 1) {
$pagingLink[] = " $page ";
} else {
$pagingLink[] = " $page ";
}
}
}
$pagingLink = implode(' | ', $pagingLink);
// return the page navigation link
$pagingLink = $first . $prev . $pagingLink . $next . $last;
}
return $pagingLink;
}
im calling it like:
$sql = "something";
$result = mysql_query(getPagingQuery($sql, $rowsPerPage));
$pagingLink = getPagingLink($sql, $rowsPerPage, $url);
now if my url is like
http://xyz/abc/list.php its working fine.
but when my url is like
http://xyz/abc/list.php?action=def
after i click on page 2 the url changes like http://xyz/abc/list.php?page2&
'action=def' part is gone so the result changes.
if i use to pass the value in $strGet as $_SERVER['QUERY_STRING']
the 1st time it is ok like http://xyz/abc/list.php?page2&action=def
but from the 2nd time onwards it gives like http://xyz/abc/list.php?page3&page2&action=def
so not getting the desired result.
whereas i want it to be like http://xyz/abc/list.php?page3&action=def
plz help.. thanxx in advance
So I consider you use $_GET['page'] ^^
$_GET['page']=$page;
$url = 'http://xyz/abc/list.php?';
foreach($_GET as $key=>$param) {
$url.=$key.'='.$param.'&';
}
use http_build_query() instead of $_SERVER['QUERY_STRING']
What i would do is before setting $page = url code. i would first echo $page before and after setting it. so that i can see exactly what the values are. And i would print echo statements before and after everytime i set $page with the url to make sure it is correct. and if in any place you can see that its not the desired output because you can see that from the echo statements then you can make the right changes to make sure the $page variable is set properly.
what i would do then to set it properly is clear the $page variable and make sure that the $page variable is then set freshly with the url.
also when setting the url make sure that the $strGet variable is also echoed out first to make sure that it is the right value that you want to set. and then set the url to the $page variable.
By doing this simple debugging you are making sure all the values are correct first and you know it is before setting them.
give it a go
let me know what happens
PK

Categories