Issue with Codeigniter Pagination And Search - php

I am trying to give facility of pagination and search keyword in one report with Code-igniter Framework.
Below is the Controller code for that Purpose:
$queryString="?start_date=".$values['start_date']."&end_date=".$values['start_date']."&keyword=".$values['keyword']."";
if($this->uri->segment(3)){
$offset=$this->uri->segment(3);
$config['base_url'] = base_url()."reports/mysearch_search/".$offset.$queryString;
}else{
$config['base_url'] = base_url()."reports/mysearch_search/".$queryString;
}
$query = $this->db->query("SELECT * FROM (`dlrReport`) WHERE LEFT(`res_submit_date`,10) >= '".$values['start_date']."' AND LEFT(`res_submit_date`,10) <= '".$values['end_date']."' AND (number LIKE '%".$values['keyword']."%' OR source LIKE '%".$values['keyword']."%')");
$config['total_rows']=$query->num_rows();
$config['per_page'] = 2;
$this->pagination->initialize($config);
$where = array('LEFT(res_submit_date,10) >=' => $values['start_date'],'LEFT(res_submit_date,10) <=' =>$values['end_date']);
$this->db->where($where);
$this->db->where("(number LIKE '%".$values['keyword']."%' OR source LIKE '%".$values['keyword']."%')");
$res = $this->db->get('dlrReport', $config['per_page'], $this->uri->segment(3));
$dlr['details']= $res->result();
$dlr['start_date']=$values['start_date'];
$dlr['end_date']=$values['end_date'];
$dlr['keyword']=$values['keyword'];
$this->load->view('mysearch',$dlr);
Getting Below link in pagination links which is not working:
http://Host/project/reports/mysearch_search/?start_date=2014-01-23&end_date=2014-01-23&keyword=/2
Url i am expecting in pagination links is like:
http://Host/project/reports/mysearch_search/2?start_date=2014-01-23&end_date=2014-01-23&keyword=
How can i will Get right Url for searching Purpose?

Here is nice example from codeignter itself. Codeigniter Pagination check this.
By default codeigniter is expecting the pagination url like this.
http://localhost/project/reports/mysearch_search/2014-01-23/2014-01-23/2
$start_date =$this->uri->segment(5);
$end_date = $this->uri->segment(6);
$keyword = $this->uri->segment(7);
and if you need this kind of url then you have to change the
http://example.com/index.php?c=test&m=page&per_page=20
then you have to change to set this on config file
$config['enable_query_strings'] set to TRUE

Related

Codeigniter Pagination showing that I am on the last page

So here is what I had before. If I'd go to ciblog/categories/posts/5/, it would take me to a page showing all posts with a category with the id of 5.
And here is what I want to do. I want to go to ciblog/categories/posts/5 and it would show be 5 posts lets say. Then when I go to ciblog/categories/posts/5/3 it would offset by 3 so now I have the next 3 posts.
Currently I have 4 posts, just for testing. If I directly through my url go to ciblog/categories/posts/5 it shows 3 posts, and if I go to ciblog/categories/posts/5/3 it shows my one other post, so the amount of posts I am getting is correct based on the url.
BUT at the bottom it always shows that I am on page 2. When I use F12 and look at the elements both my pagination links show ciblog/categories/posts/5
So its not adding on the number at the end
Here is what I have for the pagination for this page. I used print_r and everything in $config is correct.
public function posts($id, $offset=0){
$category = $this->category_model->get_category($id);
if(empty($category))
{
show_404();
}
$config['base_url'] = base_url().'categories/posts/'.$id;
$config['total_rows'] = $this->post_model->get_posts_by_category_count($id);
$config['per_page'] = 3;
$config['uri_segment'] = 3;
$config['attributes'] = array('class' => 'pagination-link');
$this->pagination->initialize($config);
$data['title'] = $category->name;
$data['posts'] = $this->post_model->get_posts_by_category($id,$config['per_page'],$offset);
$this->load->view('templates/header');
$this->load->view('posts/index', $data);
$this->load->view('templates/footer');
}
Routes:
$route['categories/posts/(:num)/(:num)'] = 'categories/posts/$1/$2';
Reference:
I have been following a tutorial here: https://www.youtube.com/watch?v=WoQTjJepDWM&index=8&list=PLillGF-RfqbaP_71rOyChhjeK1swokUIS
Code for this tutorial is here: https://github.com/bradtraversy/ciblog
I am now adding on to this. The only changes I have made are shown above
$config['base_url'] = base_url().'categories/posts/'. $id . '/' . $offset;
$config['uri_segment'] = 4;
Because your pagination depends on offset, not id of category, then you should let it find for the offset with uri_segment 4, and your base_url must send an offset variable to find the offset.

CodeIgniter - Routing issues (four segments)

Following what I thought was an issue with $this->uri->segment(), I figured out that it is actually a routing issue. Problem is that I can't really figure out what is wrong, as it looks exactly like another route I am using, which works fine, except this one has two variable segments, rather than one (for the route that is working).
The file I am trying to show is located in:
[main folder]/application/views/tasks/calendar/calendar.php
And I can load it with the command:
$route['tasks/calendar'] = 'tasks/calendar';
However, when I want to pass the current year and month as the last two segments, it does not work:
$route['tasks/calendar/(:num)/(:num)'] = 'tasks/calendar/$1/$2';
To my knowledge this should mean that a link like this should work:
(...)/index.php/tasks/calendar/2015/03
However, it does not. The full routes.php looks like this:
$route['auth/(:any)'] = 'auth/view/$1';
$route['auth'] = 'auth';
$route['projects/delete/(:any)'] = 'projects/delete/$1';
$route['projects/create'] = 'projects/create';
$route['projects/(:any)'] = 'projects/view/$1';
$route['projects'] = 'projects';
$route['(:any)'] = 'pages/view/$1';
$route['default_controller'] = 'pages/view';
$route['category'] = 'category';
$route['category/(:any)'] = 'category/view/$1';
$route['tasks/create'] = 'tasks/create';
$route['tasks/calendar/(:num)/(:num)'] = 'tasks/calendar/$1/$2';
$route['tasks/calendar'] = 'tasks/calendar';
$route['tasks'] = 'tasks';
$route['tasks/(:any)'] = 'tasks/view/$1';
And my controller, tasks.php, looks like this:
public function calendar($year = null, $month = null) {
// Calender configuration (must be done prior to loading the library
$conf = array(
'start_day' => 'monday',
'show_next_prev' => true,
'next_prev_url' => base_url() . 'index.php/tasks/calendar'
);
// Load libraries and helpers
$this->load->library('calendar',$conf);
// Set variables for $data array
$data['year'] = $year;
$data['month'] = $month;
// Show page, including header and footer
$this->load->view('templates/header', $data);
$this->load->view('tasks/calendar', $data);
$this->load->view('templates/footer');
}
And the very simple view file, calendar.php, looks like this:
<?php
echo "Selected year: ".$year." and month: ".$month;
echo $this->calendar->generate($year, $month);
What the heck am I doing wrong? The delete routes for projects works just fine...
To build on what #Craig and #CodeGodie have just said, you need to re-order your route definitions slightly.
$route['tasks'] = 'tasks/index';
// Initial route that will use $year=null, $month=null
$route['tasks/calendar'] = 'tasks/calendar';
// This route will use whatever $year, $month the user provides
$route['tasks/calendar/(:num)/(:num)'] = 'tasks/calendar/$1/$2';
You may also want to set $year=null, $month=null to valid values.
$today = getdate();
if(is_null($year) || is_null($month)){
$year = $today['year'];
$month = $today['month']
}
The problem are your routes order. These routes:
$route['(:any)'] = 'pages/view/$1';
$route['default_controller'] = 'pages/view'
should be at the very bottom of your routes list or else they will be seen prior your tasks routes.
Reference: Codeigniter User Guide - URI Routing
Note: Routes will run in the order they are defined. Higher routes
will always take precedence over lower ones.

codeigniter pagination error in id passing

$category_id=$_GET['category_id'];
$data['adsd']=$this->mymodel->select_ads_by_category($category_id);
$config["base_url"]=site_url('main/category_ads_display?category_id='.$category_id.'');
$config["total_rows"]=count($data['adsd']);
$limit=$config["per_page"]=1;
$config["uri_segment"]=3;
$config["use_page_numbers"]=TRUE;
$this->pagination->initialize($config);
if($this->uri->segment(3))
$page=($this->uri->segment(3)-1)*$limit;
else
$page=0;
Hello friends i have pasted my code above,,everything is working fine,but when i click on links of pagination the url is like this =localhost/blabla/main/category_ads_display?category_id=5/2(not working)
but i need the url to be as = localhost/blabla/main/category_ads_display/2?category_id=5(working)
please help me on this
Try this way
$category_id=$this->uri->segment(3);
$data['adsd']=$this->mymodel->select_ads_by_category($category_id);
config["base_url"]=site_url('main/category_ads_display/'.$category_id);
$config["total_rows"]=count($data['adsd']);
$limit=$config["per_page"]=1;
$config["uri_segment"]=4;
$config["use_page_numbers"]=TRUE;
$this->pagination->initialize($config);
if($this->uri->segment(4))
$page=($this->uri->segment(3)-1)*$limit;
else
$page=0;
Now your new link will be like this localhost/blabla/main/category_ads_display/5/2 for page 2 and 5 will be your category id

Site search with CodeIgniter?

I need to make a simple site search with pagination in it; could anyone tell me how to do it without affecting the URL structure? Currently I'm using the default CodeIgniter URL structure and I have removed index.php from it. Any suggestions?
You could just use a url like /search/search_term/page_number.
Set your route like this:
$route['search/:any'] = "search/index";
And your controller like this:
function index()
{
$search_term = $this->uri->rsegment(3);
$page = ( ! $this->uri->rsegment(4)) ? 1 : $this->uri->rsegment(4);
// some VALIDATION and then do your search
}
Just to update this question. It is probably best to use the following function:
$uri = $this->uri->uri_to_assoc()
and the result will then put everything into an associative array like so:
[array]
(
'name' => 'joe'
'location' => 'UK'
'gender' => 'male'
)
Read more about the URI Class at CodeIgniter.com
Don't quite understand what you mean by "affecting the url structure". Do you mean you'd want pagination to occur without the URL changing at all?
The standard pagination class in CI would allow you to setup pagination so that the only change in the URL would be a number on the end
e.g if you had 5 results to a page your urls might be
http://www.example.com/searchresults
and then page 2 would be
http://www.example.com/searchresults/5
and page 3 would be
http://www.example.com/searchresults/10
and so on.
If you wanted to do it without any change to the URL then use ajax I guess.
Code Igniter disables GET queries by default, but you can build an alternative if you want the url to show the search string.
Your url can be in the notation
www.yoursite.com/index.php/class/function/request1:value1/request2:value2
$request = getRequests();
echo $request['request1'];
echo $request['request2'];
function getRequests()
{
//get the default object
$CI =& get_instance();
//declare an array of request and add add basic page info
$requestArray = array();
$requests = $CI->uri->segment_array();
foreach ($requests as $request)
{
$pos = strrpos($request, ':');
if($pos >0)
{
list($key,$value)=explode(':', $request);
if(!empty($value) || $value='') $requestArray[$key]=$value;
}
}
return $requestArray ;
}
source: http://codeigniter.com/wiki/alternative_to_GET/

Codeigniter Pagination - I'm stumped

Ok, I followed the instructions in the example perfectly. Ultimately, pagination works, kind of.
I get all of the pages listed: 1 | 2 | > | Last. Etc.
The first one is active, like it should be. I did the querying correctly as well, because each link will result in the correct query.
However, when I click on number 2, it will show me the next set of products correctly, but it will display the pagination from the first page.
Whatever pagination button I click on, will return the main pagination set: 1 (selected) | 2 | > | Last. It never changes! I'm loosing my patience, can someone help?
I think I might know whats going on. You need to tell the pagination library which segment of the URL holds the offset.
For example, if your URL is /products/browse/all/20, you need to tell CodeIgniter that the 4th segment holds the offset
$config['uri_segment'] = 4;
The default for the library is URL segment #3. If the offset in your URL is not in position 3 and you forget to tell the pagination library this, it will interpret the wrong segment as being the offset. This can lead to the kind of behaviour you describe above where the pagination does not appear to change.
I also came across same error and finally was able to fix it. Just thought to share the code script, may be someone will be able to use it.
=====> Controller
// Default function
function index()
{
// Display listing
$this->listing();
}
function listing($argDataArr = array())
{
// Initialize pagination
$pageArr['base_url'] = $this->config->item('categoryBeAction')."/listing";
$pageArr['total_rows'] = 15; //assume
$pageArr['per_page'] = 5; //assume
//You need to tell the pagination library which segment of the URL holds the offset.
$pageArr['uri_segment'] = 4; //URL eg: http://localhost/myproject/index.php/backend/category/listing/5
$this->pagination->initialize($pageArr);
// Get list of categories
// Create data array and pass data to get function
$dataArr['limitRows'] = $pageArr['per_page'];
$dataArr['limitOffset'] = $this->uri->segment(4); //the dynamic value from this segment will be used as offSet
$viewArr['listArr'] = $this->category_model->get($dataArr);
//rest of the code...
}
======> Model
function get($argDataArr = array())
{
//Select the fields required
$this->db->select('id, name, parent_id, status');
$this->db->from($this->config->item('tbl_category','dbtables'));
$this->db->where('parent_id', $parentId);
$this->db->limit($argDataArr['limitRows'], $argDataArr['limitOffset']);
$this->db->order_by("name", "asc");
$query_result = $this->db->get();
return $query_result;
}
======> View page
<!-- Pagination -->
<tr>
<td align="right">
<?php echo $this->pagination->create_links(); ?>
</td>
</tr>
Which example?
echo $this->pagination->create_links();
^^Is this in your view?

Categories