Pagination Issue in CodeIgniter - php

I'm facing an issue with the pagination in my system. Pagination is working fine here.
But if I'm searching something in that text field and if the result is more than 5 ($config['per_page'] = 5;) its not showing the pagination buttons.
And actually, I have 6 results for the search keyword 'shihas'.
And also I can see the 6th result once I go to www.example.com/path/2 .
But still, the pagination link is not there. Please tell me a solution for this issue.
Controller:
public function index()
{
//all the posts sent by the view
$search_string = $this->input->post('search_string');
$order = $this->input->post('order');
$order_type = $this->input->post('order_type');
//pagination settings
$config['per_page'] = 5;
$config['base_url'] = base_url().'admin/posts';
$config['use_page_numbers'] = TRUE;
$config['num_links'] = 20;
$config['full_tag_open'] = '<ul>';
$config['full_tag_close'] = '</ul>';
$config['num_tag_open'] = '<li>';
$config['num_tag_close'] = '</li>';
$config['cur_tag_open'] = '<li class="active"><a>';
$config['cur_tag_close'] = '</a></li>';
//limit end
$page = $this->uri->segment(3);
//math to get the initial record to be select in the database
$limit_end = ($page * $config['per_page']) - $config['per_page'];
if ($limit_end < 0){
$limit_end = 0;
}
//if order type was changed
if($order_type){
$filter_session_data['order_type'] = $order_type;
}
else{
//we have something stored in the session?
if($this->session->userdata('order_type')){
$order_type = $this->session->userdata('order_type');
}else{
//if we have nothing inside session, so it's the default "Asc"
$order_type = 'Asc';
}
}
//make the data type var avaible to our view
$data['order_type_selected'] = $order_type;
//we must avoid a page reload with the previous session data
//if any filter post was sent, then it's the first time we load the content
//in this case, we clean the session filter data
//if any filter post was sent but we are on some page, we must load the session data
//filtered && || paginated
if($search_string !== false && $order !== false || $this->uri->segment(3) == true){
/*
The comments here are the same for line 79 until 99
if the post is not null, we store it in session data array
if is null, we use the session data already stored
we save order into the var to load the view with the param already selected
*/
if($search_string){
$filter_session_data['search_string_selected'] = $search_string;
}else{
$search_string = $this->session->userdata('search_string_selected');
}
$data['search_string_selected'] = $search_string;
if($order){
$filter_session_data['order'] = $order;
}
else{
$order = $this->session->userdata('order');
}
$data['order'] = $order;
//save session data into the session
if(isset($filter_session_data)){
$this->session->set_userdata($filter_session_data);
}
$data['count_posts']= $this->posts_model->count_posts($search_string, $order);
$config['total_rows'] = $data['count_posts'];
//fetch sql data into arrays
if($search_string){
if($order){
$data['posts'] = $this->posts_model->get_posts($search_string, $order, $order_type, $config['per_page'],$limit_end);
}else{
$data['posts'] = $this->posts_model->get_posts($search_string, '', $order_type, $config['per_page'],$limit_end);
}
}else{
if($order){
$data['posts'] = $this->posts_model->get_posts('', $order, $order_type, $config['per_page'],$limit_end);
}else{
$data['posts'] = $this->posts_model->get_posts('', '', $order_type, $config['per_page'],$limit_end);
}
}
}else{
//clean filter data inside section
$filter_session_data['search_string_selected'] = null;
$filter_session_data['order'] = null;
$filter_session_data['order_type'] = null;
$this->session->set_userdata($filter_session_data);
//pre selected options
$data['search_string_selected'] = '';
$data['order'] = 'id';
//fetch sql data into arrays
$data['count_posts']= $this->posts_model->count_posts('','');
$data['posts'] = $this->posts_model->get_posts('', '', $order_type, $config['per_page'],$limit_end);
$config['total_rows'] = $data['count_posts'];
}
//initializate the panination helper
$this->pagination->initialize($config);
//load the view
$data['main_content'] = 'admin/posts/list';
$this->load->view('includes/template', $data);
}

You can use datatable which is so real time.
DataTables is a plug-in for the jQuery Javascript library. It is a highly flexible tool, based upon the foundations of progressive enhancement, and will add advanced interaction controls to any HTML table.
Pagination, instant search and multi-column orderingSupports almost any data source:DOM, Javascript, Ajax and server-side processingEasily theme-able: DataTables, jQuery UI, Bootstrap, FoundationWide variety of extensions inc. Editor, Buttons, FixedColumns and moreExtensive options and a beautiful,
expressive APIFully internationalisableProfessional quality: backed by a suite of 2900+ unit testsFree open source software (MIT license)! Commercial support available.
Just put code:
$(document).ready(function(){
$('#myTable').DataTable();
});

Related

Code Igniter pagination does not return all the rows having the same parameters

I'm relatively new in Code Igniter and I'm trying to use the Code Igniter pagination class for the first time. I'm trying to get some rows in my database table, depending on the state, lga and category selected by the user. These three are passed to the function as parameters. I have followed the process I found on SO and some other sites to implement pagination on the page, and it seems to work, except that it doesn't return all the rows that has the specified parameters.
This what I have:
Model - Posts_model.php
public function count_lga_cat_posts($state, $lga, $category) {
return $this->db->get_where('lga_posts', array('state' => $state, 'lga' => $lga, 'category' => $category, 'display' => 'true'))->num_rows();
}
public function fetch_lga_cat_data($limit, $start) {
$this->db->limit($limit, $start);
$this->db->order_by("id", "desc");
$query = $this->db->get("lga_posts");
if ($query->num_rows() > 0) {
foreach ($query->result() as $row) {
$data[] = $row;
}
return $data;
}
return false;
}
Controller - Lga_posts.php
public function selected_state_lga_posts_category($state, $lga, $category)
{
//config for pagination
$config = array();
$uri_seg = 5;
$config["base_url"] = base_url('state2/'.$state.'/'.$lga.'/'.$category); //as specified in routes
$config["total_rows"] = $this->posts_model->count_lga_cat_posts($state, $lga, $category);
$config["per_page"] = 3;
$config["uri_segment"] = $uri_seg;
$config['use_page_numbers'] = TRUE;
$config['cur_tag_open'] = ' <a class="current">';
$config['cur_tag_close'] = '</a>';
$config['first_link'] = 'Back to first page';
$config['next_link'] = 'View more posts';
$config['prev_link'] = 'Previous posts';
$config['last_link'] = 'Jump to last page';
$config['display_pages'] = FALSE;
$this->pagination->initialize($config);
$page = ($this->uri->segment($uri_seg))? $this->uri->segment($uri_seg) : 0;
$this->db->where(array('state' => $state, 'lga' => $lga, 'category' => $category, 'display' => 'true'));
$data["results"] = $this->posts_model->fetch_lga_cat_data($config["per_page"], $page);
$str_links = $this->pagination->create_links();
$data["links"] = explode(' ',$str_links );
$data['state'] = $state;
$data['lga'] = $lga;
$data['category'] = $category;
$this->load->view('posts/lga/selected_state_lga_posts_category', $data);
When I load this page, everything seems to work fine, the pagination links are working as expected, but some rows in the table are not pulled, even though they have the same parameters as the ones that were pulled and displayed. If I change per_page config to 1, the last page gives an error "invalid argument in foreach" or something similar. I wonder if it has something to do with my query, since I do not want to get all the rows in the table, but the ones that have the selected parameters i.e. state, lga and category.
Can someone please point out to me what I'm doing wrong?

codeigniter pagination, sending parameters between functions

I have a problem with pagination and codeigniter. I have a quick_searh view from witch I am submitting the information to a index controller function and there setting the pagination and calling the quick_search method to get the data I want. It just doesnt work . I've spent more then 5 hours rewriting those methods and even starting with quick_search and then passing to index function but nothing worked, please help.
public function index(){
// search parameters config
$lawyer_name = $this->input->post('lawyer_name');
$kanzlei = $this->input->post('kanzlei');
$area_of_expertise = $this->input->post('area_of_expertise');
$post_code = $this->input->post('post_code');
$city = $this->input->post('city');
$result = $this->quick_search(
$this->uri->segment(3),
$lawyer_name,
$kanzlei,
$area_of_expertise,
$post_code,
$city);
if(isset($result)){
// pagination config
$this->load->library('pagination');
$this->load->library('table');
$config['total_rows'] = count($result);
$config['base_url'] = 'http://localhost/anwalt/index.php/search/index';
$config['per_page'] = 5;
$config['num_links'] = 5;
$this->pagination->initialize($config);
$data['search_result_array'] = $result;
$data['main_content'] = 'pages/quick_search_results';
$this->load->view('templates/home_body_content', $data);
}
}
the quick_search function:
public function quick_search($offset, $lawyer_name, $kanzlei, $area_of_expertise, $post_code, $city){
// no input in the quick search
if( empty($lawyer_name) && empty($kanzlei) && empty($area_of_expertise)
&& empty($post_code) && empty($city))
{
$result = 'nothing';
} else {
$this->load->model('quick_search_model');
$result = $this->quick_search_model->get_search_results(
$offset,
$lawyer_name,
$kanzlei,
$area_of_expertise,
$post_code,
$city
);
}
return $result;
}
the sql is like this:
$sql = "SELECT users.user_id, users.canonical_name, first_name, last_name, city, phone_number, kanzlei
from users
inner join user_normal_aos
on users.user_id = user_normal_aos.user_id
inner join normal_areas_of_expertise
on user_normal_aos.normal_areas_of_expertise_id = normal_areas_of_expertise.normal_areas_of_expertise_id
where ".implode(" AND ", $where);
if(empty($offset)){
$offset = 0;
}
$sql = $sql." LIMIT ".$offset.", 4";
The data are displayed but I dont see the pagination in there .. and even when I want to change the url for segmenting it says I dont have any data.
The view is like:
<h1>Quick search results</h1>
<?php
if($search_result_array == "nothing"){
echo "<h3>You havent inputed anything</h3>";
} else {
echo $this->table->generate($search_result_array);
}
echo $this->pagination->create_links();
As per your search variables you can use this:
$lawyer_name = $this->input->post('lawyer_name');
$kanzlei = $this->input->post('kanzlei');
$area_of_expertise = $this->input->post('area_of_expertise');
$post_code = $this->input->post('post_code');
$city = $this->input->post('city');
/*pagination start*/
$this->load->library('pagination');
$config['base_url'] = base_url().'index.php/index/lawyer/'.$lawyer_name.'/kanzlei/'.$kanzlei.'/area_of_expertise/'.$area_of_expertise.'/post_code/'.$city.'/page/';
$config['total_rows'] = $this->model->count_all_results(); ###implement this function to count all the vodeos as per the search variables, just use the same function as "quick_search" but without the limit clause
$config['per_page'] = count($result);;
$config['uri_segment'] = 10;
$config['next_link'] = 'Next';
$config['prev_link'] = 'Prev';
$config['cur_tag_open'] = '<span class="active_page">';
$config['cur_tag_close'] = '</span>';
$this->pagination->initialize($config);
/*pagination end*/
You can not use $this->pagination->create_links(); method in view.
Use $data['pagination'] = $this->pagination->create_links(); in controller just before loading view
and echo $pagination in view
hope this will help you.

How to create pagination links when combining data from two different queries

I have a controller with a method that looks something like this:
public function browsecategory($category_id)
{
//find any subcategories for this category
$this->load->model('category/category_model');
$this->load->model('category/product_category_model');
$records['categories'] = $this->category_model->find_all_by('parent_id', $category_id);
//add some product data too.
$records['products'] = $this->product_category_model->find_all_by('category_id', $category_id);
Template::set('records', $records);
Template::render();
}//end browsecategory
All the examples I've seen for the codeigniter pagination "stuff" is using one query.
I need to combine two data sets and serve on one view.
Any suggestions?
EDIT 1
I've tried to follow MDeSilva's suggestion below. And although the pagination object is correctly calculating the number of links to create, all items appear on all pages.
Here's the code in the model that gets the data:
public function get_categories_and_products($limit=12, $offset=0, $category_id=null)
{
print '<BR>the function got the following offeset:'.$offset;
$query = "(SELECT cat.category_id, cat.title, cat.image_thumb, cat.deleted, cat.display_weight ";
$query = $query."FROM bf_categories cat ";
$query = $query."WHERE cat.parent_id=".$category_id;
$query = $query." AND cat.category_id <>".$category_id;
$query = $query.") UNION (";
$query = $query."SELECT p.product_id, p.name, p.image_thumb, p.deleted , p.display_weight";
$query = $query." FROM bf_product p ";
$query = $query."Inner join bf_product_category cp ";
$query = $query."on p.product_id=cp.product_id ";
$query = $query."Where cp.category_id=".$category_id.")";
$this->db->limit($limit, $offset);
$catsandprods= $this->db->query($query);
return $catsandprods->result() ;
}
And here's the code in the controller:
public function browsecategory($category_id, $offset=0)
{
$this->load->library('pagination');
$total = $this->product_model->get_cats_prods_count($category_id);
$config['base_url'] = site_url('/product/browsecategory/'.$category_id);
$config['uri_segment'] = 4;
$config['total_rows'] = $total;
$config['per_page'] = 5;
$config['num_links'] = 10;
$this->pagination->initialize($config);
$offset = ($this->uri->segment($config['uri_segment'])) ? $this->uri->segment($config['uri_segment']) : 0;
print $offset;
//Call the model function here to get the result,
$records= $this->product_model->get_categories_and_products(5,$offset,$category_id);
//add to breadcrumb trail
$this->build_bread_crumb_trail($category_id);
$breadcrumbs = $this->breadcrumbs->expand_to_hyperlinks();
Template::set('currentcategory',$category_id);
Template::set('breadcrumbs', $breadcrumbs);
Template::set('records', $records);
Template::render();
}
I've debugged and I can see that the line of code "$this->db->limit($limit, $offset);" in the model is not working. It always returns the full record set...
Can you tell me what I'm missing?
Thanks.
This is the way to generate pagination links in CI, for your requirement have a query with a join,
public function index($offset = 0) {
$language_id = 1;
$artwork_id = null;
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
$artwork_id = $this->input->post('serach_artwork_id', TRUE) ? $this->input->post('serach_artwork_id', TRUE) : null;
$data['artwork_id'] = $artwork_id;
}
$this->load->library('pagination');
$limit = 10;
$total = $this->Artwork_model->get_artwork_count($language_id, $artwork_id);
$config['base_url'] = base_url().'artwork/index/';
$config['total_rows'] = $total;
$config['per_page'] = $limit;
$config['uri_segment'] = 3;
$config['first_link'] = '<< First';
$config['last_link'] = 'Last >>';
$config['next_link'] = 'Next ' . '>';
$config['prev_link'] = '<' . ' Previous';
$config['num_tag_open'] = '<span class="number">';
$config['num_tag_close'] = '</span>';
$config['cur_tag_open'] = '<span class="current"><a href="#">';
$config['cur_tag_close'] = '</a></span>';
$this->pagination->initialize($config);
//Call the model function here to get the result,
$data['artworks'] = $this->Artwork_model->get_artworks($language_id, $limit, $offset, $artwork_id);
$this->template->write('title', 'Artwork : Manage Artwork');
$this->template->write_view('content', 'artwork/index', $data);
$this->template->render();
}
Here is an example for query with multiple joins in the model
public function get_artworks($language_id = 1, $limit = 10, $offset = 0, $arwork_id = null)
{
$this->db->select('a.id, a.price, a.is_shop, at.title,at.status,at.date_added,ats.name as artist_name');
$this->db->from('artworks a');
$this->db->join('artwork_translations at', 'a.id = at.artwork_id');
$this->db->join('artists ats', 'a.artist_id = ats.id');
$this->db->where('at.language_id', $language_id);
if(!is_null($arwork_id) && !empty($arwork_id) && $arwork_id != 'all')
{
$this->db->where('a.id =', $arwork_id);
}
$this->db->order_by('a.id DESC');
$this->db->limit($limit, $offset);
$artworks = $this->db->get();
return $artworks->result();
}
In the View
<?= $this->pagination->create_links(); ?>
The pagination class doesn't care about the how the data source is constructed, just so you hand it the data result object it wants. So you would just pass limits & offsets into your data queries, or else pull all your data and slice it up afterwards.
However, I don't really understand how you are thinking to combine these different bits of data into a single result to display - are you trying to display all categories, then paginate the products? If so, you are set up incorrectly
Simply use PHP function array_merge
<?php $beginning = 'foo'; $end = array(1 => 'bar');
$result = array_merge((array)$beginning, (array)$end);
$this->load->view('view.php', $result);
?>
and extract according to keys for array used.
It is really simple & working

CodeIgniter Paging class, active link not working

I am using the paging class of the codeigniter for the first time. Everything else is working fine, but whichever page I am going, the active link is always the [1] and it doesn't change. Also the next button is always linked to the first page. Culdn't figure out why ! Please help !
Controller
public function unverified_images()
{
$data['title'] = 'Choose from the below Images to verify them >>';
$data['total_rows'] = $this->admin_model->all_unverified_images();
$config['base_url'] = base_url().'index.php/admin/admin/unverified_images';
$config['total_rows'] = $data['total_rows']->num_rows();
$config['per_page'] = 1;
$config['num_links'] = 8;
$config['full_tag_open'] = '<div class="pagination">';
$config['full_tag_close'] = '</div>';
$this->pagination->initialize($config);
$data['query'] = $this->db->where('image_status', 0)
->get('tbl_img', $config['per_page'], $this->uri->segment(4));
$data['links']=$this->pagination->create_links();
$this->load->view('admin/image_verify', $data);
}
public function verify_image()
{
$data['title'] = 'Choose from the below Images to verify them >>';
$data['msg'] = $this->admin_model->verify_image();
$data['query'] = $this->admin_model->all_unverified_images();
redirect('admin/admin/unverified_images');
}
Model
function all_unverified_images()
{
$this->db->where('image_status', 0);
$query = $this->db->get('tbl_img');
return $query;
}
View
<?php echo $links; ?>
Sound like that CI can't figure out what page you supposed to be on.
Try adding the uri_segment or the cur_page for the $config array.
The uri_segment should tell CI what part of the url holds the current page number, from your example code it seem to be 4 (from the query) while CI's default is 3.

In Codeigniter Pagination's generated page links, page 1 is always selected

I'm about to pull my hair over this!
On initial load of my page with pagination (by CI), all rows are displayed, even if I only want 3. On click of other pages, however, it works fine (the correct rows are displayed), but Page 1 is always "selected" (not clickable), even if I click on Page 2, 3, etc.
Any ideas?
My CONTROLLER:
function album($type, $album_id, $album_name) {
$this->load->library('pagination');
$config['base_url'] = base_url("photo_store/album/$type/$album_id/$album_name/");
$config['total_rows'] = $this->Media_model->get_photos($album_id, 'display_date DESC', NULL, NULL, TRUE);
$config['per_page'] = 3;
$this->pagination->initialize($config);
$album_photos = $this->Media_model->get_photos($album_id, 'display_date DESC', $config['per_page'], $this->uri->segment(6), FALSE);
$this->_load_view(array(
/* some other variables here */
'album_photos' => $album_photos
));
)
private function _load_view($more_data) {
$data = array_merge($more_data, array( /* some other variables here */ ));
$this->load->view('template', $data);
}
My MODEL:
public function get_photos($album_id=NULL, $order_by='display_date DESC', $limit=NULL, $offset=NULL, $count=FALSE) {
$result = array();
$query = $this->db->select('medium.*')->join('medium', "$this->item.medium_id = medium.id", 'inner')->order_by($order_by);
$limit = $limit ? $limit : '0';
$offset = $offset ? $offset : '0';
if ($limit!=='0' && $offset!=='0') {
$query->limit($limit, $offset);
}
if ($album_id) { $result = $query->get_where($this->item, array('album_id' => $album_id)); }
else { $result = $query->get($this->item); }
if ($count){ return $result->num_rows(); }
else { return $result->result(); }
}
My VIEW:
foreach ($album_photos as $photo) {
//display photos here
}
echo $this->pagination->create_links();
You can just add this to the config array so the pagination knows where to find the current page:
$config['uri_segment'] = 4;
I believe part of the problem is coming in here:
if ($limit!=='0' && $offset!=='0') {
$query->limit($limit, $offset);
}
Since you don't have an else part for your statement, the query is never limited for that first page.
I suggest you change that code to
if ($limit!=='0') {
$query->limit($limit, $offset);
}
or even just
$query->limit($limit, $offset);
since $limit should theoretically never be null or 0 because you've set it to 3. $offset, unless set, should be 0 so you could replace null with it in your model's function,
When there are more than 3 uri segments passed in the url, selected page of pagination will not be displayed correctly, it will highlight the first page all the time.
Pagination is working, but the selected page is not diplayed correctly.
To solve this, solution:
go to Pagination.php file which is located at system->libraries->Pagination.php
just simply set
var $uri_segment = 4;// or 5 or 6;
It will work.
You can just add this to the config array so the pagination knows where to find the current page:
$config['uri_segment'] = 4; // Your appropriate uri segment: 5 or 6
Try to code your controller like below:
public function index($page=''){
//...
$page = ($page!='')? $page : 0;
$config["cur_page"] = $page;
//...
}

Categories