customized query in codeigniter pagination class - codeigniter

I am using codeigniter pagination class and am stuck in this code!
the following code reads the whole columns from the employees table but my query contains a join. I do not really know how I am going to run my own query using the config settings!
$config['per_page'] = 20;
$view_data['view_data'] = $this->db->get('employees', $config['per_page'], $this->uri->segment(3));
My own query:
$this->db->select('emp.code as emp_code,emp.fname as emp_fname,emp.lname as emp_lname,emp.faname as emp_faname,emp.awcc_phone as emp_phone,emp.awcc_email as emp_email,position as position,dep.title as department');
$this->db->from('employees as emp');
$this->db->join('departments as dep','dep.code=emp.department_code');
$this->db->where('emp.status = 1');
$employees_list = $this->db->get();
return $employees_list;

You approach is totally wrong.
In Controller do it like this
$this->load->model('mymodel');
$config['per_page'] = 20;
$view_data['view_data'] = $this->mymodel->getEmployees($config['per_page'], $this->uri->segment(3));
Modle function
function getEmployees($limit = 10 , $offset = 0)
{
$select = array(
'emp.code as emp_code',
'emp.fname as emp_fname',
'emp.lname as emp_lname',
'emp.faname as emp_faname',
'emp.awcc_phone as emp_phone',
'emp.awcc_email as emp_email',
'position as position',
'dep.title as department'
);
$this->db->select($select);
$this->db->from('employees as emp');
$this->db->join('departments as dep','dep.code=emp.department_code');
$this->db->where('emp.status',1);
$this->db->limit($offset , $limit);
return $this->db->get()->result();
}
See this tutorial for usage

Related

codeigniter pagination pulling item more then once

This is a very irritating issue. I have my codeigniter pagination set up and so I thought working, but looking at it closer it seems that on the last page it's pulling in previous results to fill the page in.
So say I want ten per page and have fourteen results. The first page has ten results, and so does the second. When it should be the first has ten and the second has four. It would be fine if it was just repeating one result, but it's irritating to have to scroll through six previous results. Any help would be much appreciated.
in my controller I have the pagination code
$config = array();
$config["base_url"] = base_url()."myStories/".$id;
$config["total_rows"] = $this->data_model->my_count();
$config["per_page"] = 10;
$config["uri_segment"] = 3;
$config['num_links'] = 2;
$choice = $config["total_rows"] / $config["per_page"];
//$config["num_links"] = round($choice);
$this->pagination->initialize($config);
$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
$this->load->view('userStory_view', array(
'query' => $this->data_model->pullMyStories($config['per_page'], $page),
'links' => $this->pagination->create_links(),
'user' => $this->users_model->getUser($this->user->user_id),
));
and then in my model I have the count and then the actual results coming back
public function my_count() {
//This counts all the stories that belong to that author
$author = $this->uri->segment(2);
$this->db->where('author', $author);
$this->db->where(array('approved !=' => 'd'));
$query = $this->db->get('story_tbl');
return $query->num_rows();
}
public function pullMyStories($limit, $start){
//This pulls back all the stories that belong to that author
$this->db->limit($limit, $start);
$this->db->order_by("date", "desc");
$author = $this->uri->segment(2);
$this->db->where(array('approved !=' => 'd'));
$this->db->where('author', $author);
$story = $this->db->get('story_tbl');
return $story->result();
}
the route I have set up that does work
$route['myStories/(:any)'] = "story/viewStories/$1";
I thought initially that my count was count was wrong, but even with a count of 14, 20 results come back.
For further information I am more than positive that my baseUrl is correct. I have modified my .htaccess to get rid of the index.php and have edited my route file to make the controller disappear from the url. To try and make it easy to remember for the user.
I am also very sure that the uri segments are correct. If they were not correct then my page would not be coming up at all.
I have tried all the normal solutions and nothing has worked. That is why I am asking here and why I have placed a bounty on this question.
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 = 0; // 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 $use_page_numbers = FALSE; // Use page number for segment instead of offset
var $first_link = 'First';
var $next_link = '->';
var $prev_link = '<-';
var $last_link = 'Last';
var $uri_segment = 2;
var $full_tag_open = '';
var $full_tag_close = '';
var $first_tag_open = '';
var $first_tag_close = ' ';
var $last_tag_open = ' ';
var $last_tag_close = '';
var $first_url = ''; // Alternative URL for the First Page.
var $cur_tag_open = ' <strong>';
var $cur_tag_close = '</strong>';
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 $page_query_string = FALSE;
var $query_string_segment = 'per_page';
var $display_pages = TRUE;
var $anchor_class = '';
Your problem is that you are passing the wrong parameters to your pullMyStories method. On the first page you will be apply the following limit to your query
LIMIT 0,10
Then on the second page
LIMIT 1,10
Then on the third
LIMIT 2,10
So you pagination is only moving forward one item at a time instead of ten. So you need to change this
'query' => $this->data_model->pullMyStories($config['per_page'], $page),
To this
'query' => $this->data_model->pullMyStories($config['per_page'], ($page * $config['per_page'])),
I recently tried so hard to about ci pagination.
I think, your codes right.
What exactly uri string on second page?.. And this listing function is index() ?
Try if it works for you:
$config = array();
$config["base_url"] = base_url()."myStories/"; #change in base url
$config["total_rows"] = $this->data_model->my_count();
$config["per_page"] = 10;
$config["uri_segment"] = 3;
$config['num_links'] = 2;
#$choice = $config["total_rows"] / $config["per_page"];
//$config["num_links"] = round($choice);
$this->pagination->initialize($config);
#$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0; #no need of calculation here
$this->load->view('userStory_view', array(
'query' => $this->data_model->pullMyStories($this->uri->segment(3)), #change here send the offset directly
'links' => $this->pagination->create_links(),
'user' => $this->users_model->getUser($this->user->user_id),
));
function pullMyStories($offset = 0){
$story = $this->db->where('author', $this->uri->segment(2))->where('approved != d')->order_by("date", "desc")->get('story_tbl', 10, $offset);
return $story->result();
}
Try this. You just need to change the base_url in the correct way. Also be careful and check if you are getting a right number for uri_segment. If not, you can change the number, and get the correct.
// $config = array();
// MUST CHNGE IT I just tell the with simple example. If you have index.php, c name and method name.
$config["base_url"] = base_url()."index.php/controller_name/function_name/";
$config["total_rows"] = $this->data_model->my_count();
$config["per_page"] = 10;
$config["uri_segment"] = 3; // BE CARFULL with uri_segment. You need to print it, and be shre that you are getting the right number
$config['num_links'] = 2;
$this->pagination->initialize($config);
$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
$this->load->view('userStory_view', array(
'query' => $this->data_model->pullMyStories($config['per_page'], $page),
'links' => $this->pagination->create_links(),
'user' => $this->users_model->getUser($this->user->user_id),
));
I update my code, I comment and $config = array();
I did it today in my computer this, and it works. I know that you maybe checked it hundred times, but Check in details it again.
UPDATE with my example:
function index() {
$data['page_title'] = "Items";
$config['base_url'] = base_url() .'index.php/items/index/';
$config['total_rows'] = $this->items_model->count_items(); // Count items from DB
$config['per_page'] = 10;
$config['uri_segment'] = 3;
// Customize
$config['next_link'] = FALSE;
$config['prev_link'] = FALSE;
$config['first_link'] = 'first';
$config['last_link'] = 'last';
$config['cur_tag_open'] = '<a class="current">';
$config['cur_tag_close'] = '</a>';
$this->pagination->initialize($config);
$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
$data['items'] = $this->items_model->get_items($config["per_page"], $page);
$this->load->view('invoice-items', $data);
}
In your controller:
$page = $this->uri->segment(3,0);
Then:
public function pullMyStories($limit, $start){
$author = $this->uri->segment(2);
$this->db
->select('*')
->where('approved !=', 'd')
->where('author', $author)
->order_by('date', 'DESC')
->limit($limit, $start);
$story = $this->db->get('story_tbl');
return $story->result();
Also where do you load the library using the line below?
$this->load->library('pagination');
I'm just gonna throw this in and hope it helps in some way, because I've tested and it works for me. I've made the following assumptions for testing:
id (as in "myStories/".$id in the controller) is taken from $this->uri->segment(2)
story_tbl fields I created were id, author, date
My test files were as follows:
Controller MyStories.php:
public function index()
{
//loading library, model, and assumptions
$this->load->library('pagination');
$this->load->model('m_page', 'data_model');
$id = $this->uri->segment(2);
//
//
//Your code from here...
//
//
$config = array();
$config["base_url"] = $this->config->site_url("myStories/".$id);
$config["total_rows"] = $this->data_model->my_count();
$config["per_page"] = 3;
$config["uri_segment"] = 3;
$config["num_links"] = round($config["total_rows"] / $config["per_page"]);
$this->pagination->initialize($config);
$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
$data = array();
$data['query'] = $this->data_model->pullMyStories($config['per_page'], $page);
$data['links'] = $this->pagination->create_links();
$data['config'] = $config;
//$data['user'] = $this->users_model->getUser($this->user->user_id);
$this->load->view('userStory_view', $data);
}
BTW, you really want to be using the site_url and not base_url when defining the pagination base_url.
I also commented out the 'user' data in the controller simply because you never gave any info on that.
My test view, userStory_view.php:
<?php echo $links;?>
<!-- -->
<hr>
total rows: <?php echo $config['total_rows'];?>
<hr>
<?php echo $this->db->last_query();?>
<hr>
<!-- -->
<?php foreach ($query as $row):?>
<?php echo $row->author.'<hr>';?>
<?php endforeach;?>
I made no changes to your Model, so no need to show that here.
I added the following line to routes.php:
$route['myStories/(:any)'] = "myStories";
As I said, everything worked for me. Besides my formatting, the only changes I really made were the use of site_url() instead of base_url(), and the commenting of the user data. So pretty stuck as to why you're having issues I'm afraid.
As far as it seems your overall pagination functionality seems to correct. what i want check would the sql query returned in each function and parameters passed to those function coz $author variable has to global and try
$this->db->last_query();
on your both functions my_count() and pullMyStories($limit, $start) and check those function returning right results.
U might also can try writing direct sql query with changing parameters like.
$sql = "SELECT * FROM some_table WHERE author = ? LIMIT ?, ?";
$this->db->query($sql, array($author, $start, $limit));
As i am seeing this would be mostly of query might have been wrong .
Hope this helps.

pagination doesn't work in codeigniter

I have successfully created pagination on some of the pages on the application on which I am working with, but I can't make it on this one:
I have 7 records in the database, and when
page is displayed all 7 records are displayed instead of 5, as I would like to be.
Sure enough, links for the paging are not displayed.
Here is my controller code:
public function displayAllFaqCategories()
{
//initializing & configuring paging
$currentUser = $this->isLoggedIn();
$this->load->model('faqCategoriesModel');
$this->db->order_by('sorder');
$limit = 5;
$offset = 3;
$offset = $this->uri->segment(3);
$this->db->limit(5, $offset);
$data['faq_categories'] = $this->faqCategoriesModel->selectCategoriesAndParents();
$totalresults = $this->db->get('faq_categories')->num_rows();
//initializing & configuring paging
$this->load->library('pagination');
$config['base_url'] = site_url('/backOfficeUsers/faqcategories');
$config['total_rows'] = $totalresults;
$config['per_page'] = 5;
$config['uri_segment'] = 3;
$this->pagination->initialize($config);
$errorMessage = '';
$data['main_content'] = 'faq/faqcategories';
$data['title'] = 'FAQ Categories';
$this->load->vars($data,$errorMessage);
$this->load->vars($currentUser);
$this->load->view('backOffice/template');
} // end of function displayAllFaqCategories
And here is my model function code:
public function selectCategoriesAndParents($selectWhat = array())
{
$data = array();
$query = $this->db->query("SELECT fq . * , COALESCE( fqp.$this->parent_name, '0' ) AS parentname
FROM $this->table_name AS fq
LEFT OUTER JOIN $this->table_name AS fqp ON fqp.catid = fq.parentid");
if($query->num_rows() > 0)
{
foreach($query->result_array() as $row)
{
$data[] = $row;
}
}
$query->free_result();
return $data;
} // end of function selectCategoriesAndParents
In the view, bellow of the table with the records I have the following code:
<?php echo $this->pagination->create_links();?>
Any help will be deeply appreciated.
Regards,Zoran
You've mixed two different things together I think. You're partially using the ActiveRecord class of CI, but then running the query yourself.
The simplest change would be:
// get all the rows
$data['faq_categories'] = $this->faqCategoriesModel->selectCategoriesAndParents();
// figure out the count of all of them
$totalresults = count($data['faq_categories']);
// only take some of the rows of the array, instead of keeping all of them and then showing all 7 of your records
$data['faq_categories'] = array_splice($data['faq_categories'], $offset, $limit);
Hopefully that should fix it!
To further explain what the original problem is, I think when you run this:
$totalresults = $this->db->get('faq_categories')->num_rows();
It takes the previous line $this->db->limit(5, $offset); into account, so it only returns 5 rows. Then, when you tell the pagination library that you only want to show 5 per page, the library thinks that it is actually showing all the results, so there is no need for pagination links!
Edit like this
$offset = $this->uri->segment(3) ? $this->uri->segment(3) : 0;

Displaying database value

I am trying to display data from database using Codeigniter's table and pagination library. In my model, apart from other column I want to fetch information of column "batchid" from my table "batch" ,but don't want to show it in the view file when I am displaying the other data.
But since I have included the "batchid" in this-(in the following)
$this->db->select('batchname, class, batchid, batchinstructor');
It is showing all the information of the column "batchid" in the view, which I don't want. I just want to retrieve the value of batchid to use it for anchoring "batchname".
I have tried a lot but it won't work. Would you please kindly help me?
Thanks in Advance
Here is my model
//Function To Create All Student List
function batch_list()
{
$config['per_page'] = 15;
$this->db->select('batchname, class,batchid, batchinstructor');
$this->db->order_by("batchid", "desc");
$rows = $this->db->get('batch',$config['per_page'],$this->uri->segment(3))->result_array();
$sl = $this->uri->segment(3) + 1; // so that it begins from 1 not 0
foreach ($rows as $count => $row)
{
array_unshift($rows[$count], $sl.'.');
$sl = $sl + 1;
$rows[$count]['batchname'] = anchor('batch_list/get/'.$row['batchid'],$row['batchname']);
$rows[$count]['Edit'] = anchor('update_student/update/'.$row['batchname'],img(base_url().'/support/images/icons/edit.png'));
$rows[$count]['Delete'] = anchor('report/'.$row['batchname'],img(base_url().'/support/images/icons/cross.png'));
}
return $rows;
}
//End of Function To Create All Student List
Here is my controller
function index(){
$this->load->helper('html');
$this->load->library('pagination');
$this->load->library('table');
$this->table->set_heading('Serial Number','Batch Name','Class','Batch Instructor','Edit','Delete');
$config['base_url'] = base_url().'batchlist/index';
$config['total_rows'] = $this->db->get('batch')->num_rows();
$config['per_page'] = 15;
$config['num_links'] = 5;
$config['full_tag_open'] = '<div class="pagination" align="center">';
$config['full_tag_close'] = '</div>';
$this->pagination->initialize($config);
$data['tab'] = "Batch List";
$this->load->model('mod_batchlist');
$data['records']= $this->mod_batchlist->batch_list();
$data['main_content']='view_batchlist';
$this->load->view('includes/template',$data);
}
I'm not sure what you're doing in your view, but you can add rows manually by looping through your dataset:
foreach ($records->result() as $r)
{
$this->table->add_row($r->serial,
$r->batchname,
$r->class,
$r->batchinstructor,
$r->edit,
$r->delete
);
}
echo $this->table->generate();
In this way, you control what data goes to your table.

Codeigniter: Can I return multiple values from the same function?

I would like to return the query results along w/ the row count without having to run multiple queries. Is this possible in Codeigniter? The following works for returning the query results, but is it possible to also count the number of entries found?
Controller:
$data['records'] = $this->item_model->searchItem($item_name);
Model:
$query = $this->db->query($sql, array($this->user_id, '%'.$item_name.'%'));
return $query->result();
$bindings = array($this->user_id, '%'.$item_name.'%');
$records = $this->db->query($sql, $bindings)->result();
return array(
'records' => $records,
'count' => count($records),
);
Then, in your controller:
$query = $this->item_model->searchItem($item_name);
$data['records'] = $query['records'];
$data['count'] = $query['count'];
Option one
$query = $this->db->query($sql, array($this->user_id, '%'.$item_name.'%'));
$data['result'] = $query->result();
$data['rows'] = $query->num_rows();
return $data;
Option two
// model
$query = $this->db->query($sql, array($this->user_id, '%'.$item_name.'%'));
return $query;
// controller
$data['query'] = $this->item_model->searchItem($item_name);
// then you have $data['query']->result();
// and $data['query']->num_rows();
You can send as many variables from a function as you want ..However plz remember that a function is supposed to do one UNIT of work . thus this rule must not be violated.
we can used contrel structure
if this {return A;} elseif () {return B;} else {return C;}
ALso we can send (bundle) variables in an array and send

Codeigniter pagination problem

I basically can’t get the pagination bit to work, I did before I changed my database query and now I’m stuck.
My model looks like:
function get_properties($limit, $offset) {
$location = $this->session->userdata('location');
$property_type = $this->session->userdata('property_type');
if($property_type == 0)
{
$sql = "SELECT * FROM properties ";
}
// more queries here
$sql .= " LIMIT ".$limit.", ".$offset.";";
$query = $this->db->query($sql);
if($query->num_rows() > 0) {
$this->session->set_userdata('num_rows', $query->num_rows());
return $query->result_array();
return FALSE;
}
}
}
and my controller looks like:
function results() {
$config['base_url'] = base_url().'/properties/results';
$config['per_page'] = '3';
$data['properties_results'] = $this->properties_model->get_properties($config['per_page'], $this->uri->segment(3));
$config['total_rows'] = $this->session->userdata('num_rows');
$this->pagination->initialize($config);
$config['full_tag_open']='<div id="pages">';
$config['full_tag_close']='</div>';
$data['links']=$this->pagination->create_links();
$this->load->view('properties_results',$data);
}
please help…its screwing up!
The reason it's not working is that you never get the total_rows. You get the total_rows via this query, but it already has an offset and a limit:
$sql .= " LIMIT ".$limit.", ".$offset.";";
$query = $this->db->query($sql);
To fix this you should add a function to your model:
function get_all_properties()
{
return $this->db->get('properties');
}
Then in your controller, instead of:
$config['total_rows'] = $this->session->userdata('num_rows');
Do:
$config['total_rows'] = $this->properties_model->get_all_properties()->num_rows();
This should fix your pagination. Other than this your code has some strange things. E.g. return FALSE; in get_properties will NEVER execute. And why are you storing so much data in sessions. This is not necessary and not a good idea in my opinion.

Resources