Displaying database value - codeigniter

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.

Related

Codeigniter pagination is not passing the correct link value in url

I have created a pagination in codeigniter, In that I have totally 13 records and i want to display 5 records in each page. When i click on the pagination link number 2,It should pass value 2 in url and it show the next 5 records but I am getting value 5 in url instead of 2.
My controller code:
public function activities($page_num = 1){
$config =array();
$config['base_url'] = base_url().'admin/skills/activities';
$config['per_page'] = 5;
$config['total_rows'] = $this->skill_model->all_activities(0,'',''); // I will get the total count from my model
if(empty($page_num))
$page_num = 1;
$limit_end = ($page_num-1) * $config['per_page']; //end limit
$limit_start = $config['per_page']; // start limit
$this->pagination->first_url = $config['base_url'].'/1';
$this->pagination->initialize($config);
$data['activity_list'] = $this->skill_model->all_activities(1,$limit_start,$limit_end);
}
This is my view code:
<?php echo '<div class="pagination" style="float:right;">'.$this->pagination->create_links().'</div>'; ?>
My Model part:
function all_activities($flag,$limit_start,$limit_end){
$this->db->select('*');
$this->db->from('skills_activities');
//echo $limit_start." ".$limit_end;
if($flag == 1 ){
$this->db->limit($limit_start, $limit_end);
$query = $this->db->get();
return $query->result_array();
} else {
$query = $this->db->get();
return $query->num_rows();
}
}
When i click on pagination link I am getting the following url:
http://192.168.1.97/projects/homecare/admin/skills/activities/5
but I should get:
http://192.168.1.97/projects/homecare/admin/skills/activities/2
I don't know where i have done a mistake.
can anybody help me?
Thanks in advance.
$config['use_page_numbers'] = true;
This will produce page number in the url instead of record number. By default its false.
So you controller will look like this
public function activities($page_num = 1)
{
$config =array();
$config['base_url'] = base_url().'admin/skills/activities';
$config['per_page'] = 5;
$config['use_page_numbers'] = true;//you missed this line
$config['total_rows'] = $this->skill_model->all_activities(0,'',''); // I will get the total count from my model
if(empty($page_num)) $page_num = 1;
$limit_end = ($page_num-1) * $config['per_page']; //end limit
$limit_start = $config['per_page']; // start limit
$this->pagination->first_url = $config['base_url'].'/1';
$this->pagination->initialize($config);

codeigniter's pagination offset not working

In CI's pagination, the data index should follow the offset. For example : if the limit is 10 then the 2nd index should have 10 offset, which means the index will start from 11 to 20.
I followed some tutorials, but i still cant get this offset thing works correctly. My index always reseted to 1 each time i click the differet pagination index.
This is my pagination code, note that i have tried to echo the $offset and the value is true (in 2nd index = 10, in 3rd index = 20, with $limit = 10) so i dont know why its not working:
public function index($offset = 0) {
//check authorization
if(!isset($_SESSION['username']))
redirect('backend_umat/login');
// the $offset value is true, but the index is still reseted to 1
echo $offset;
$limit = 10;
$result = $this->umat_m->get_umat($limit, $offset);
//pagination
$config['base_url'] = site_url('/backend_umat/index');
$config['total_rows'] = $result['num_rows'];
$config['per_page'] = $limit;
$config['uri_segment'] = 3;
$config['full_tag_open'] = '<div id="pagination">';
$config['full_tag_close'] = '</div>';
$this->pagination->initialize($config);
$data['pagination'] = $this->pagination->create_links();
And this is my model :
public function get_umat($limit, $offset) {
$this->db->select('*')->from('msumat')->limit($limit, $offset)->
join('mskelas', 'msumat.kelas_id = mskelas.kelas_id');
$q = $this->db->get();
$result['rows'] = $q->result();
$result['num_rows'] = $this->db->select('*')->from('msumat')->
join('mskelas', 'msumat.kelas_id = mskelas.kelas_id')
->get()->num_rows();
return $result;
Thanks for your help :D
public function index() {
//check authorization
if(!isset($_SESSION['username']))
redirect('backend_umat/login');
// the $offset value is true, but the index is still reseted to 1
//pagination
$config['base_url'] = base_url().'backend_umat/index';
// basically you need a separate query to return only numrows
$config['total_rows'] = ?;
$config['per_page'] = 10;
$config['uri_segment'] = 3;
$config['full_tag_open'] = '<div id="pagination">';
$config['full_tag_close'] = '</div>';
$this->pagination->initialize($config);
$offset = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
$result = $this->umat_m->get_umat( $config['per_page'], $offset);
$data['pagination'] = $this->pagination->create_links();
Here try this, i changed some code hope this works. Basically i intitialized first the pagination config, before calling anything from the model. Just do a separate query to get the numrows.
Controller
site.com/<controller>/index/<page>
public function index($offset = 0) {
//check authorization
if(!isset($_SESSION['username']))
redirect('backend_umat/login');
$limit = 10;
$offset = (int) $offset;
$result = $this->umat_m->get_umat($limit, $offset);
//pagination
$config['base_url'] = site_url('/backend_umat/index');
$config['total_rows'] = $result['num_rows'];
$config['per_page'] = $limit;
$config['uri_segment'] = 3;
$config['full_tag_open'] = '<div id="pagination">';
$config['full_tag_close'] = '</div>';
$this->pagination->initialize($config);
$data['pagination'] = $this->pagination->create_links();
Model
public function get_umat($limit, $offset) {
$result['rows'] = $this->db
->select('SQL_CALC_FOUND_ROWS, msumat.*, mskelas.*', FALSE)
->limit($limit, $offset == 1 ? 0 : $offset)
->join('mskelas', 'msumat.kelas_id = mskelas.kelas_id')
->get('msumat')
->result();
$req = $this->db->query('SELECT FOUND_ROWS()')->row_array();
$result['num_rows'] = $req['FOUND_ROWS()'];
return $result;
}
To not have to rewrite a second sql req, you can use SQL_CALC_FOUND_ROWS to retrieve the total if the request did not contain a LIMIT statement. But this can be slower than two requests.
I used FALSE as second arguments in the select() in order that CI not tries to protect field or table names with backticks.
->select('*'): is useless if you want all fields, CI will do it by default if select method was not called.
->get()->num_rows(): use instead ->count_all_results([table]).
First, thanks to tomexsans and lighta for their help. Sorry, i made a "stupid" mistake - which took about 2-3 hours to realize -, the index is not following the $offset because i FORGET to use that variable. I use an integer that i reset to 1 everytime the page load, so the index will reset to 1 forever :P

How to validate duplicate entries before inserting to database - Codeigniter

I have developed simple application, i have generated checkbox in grid dynamically from database, but my problem is when user select the checkbox and other required field from grid and press submit button, it adds duplicate value, so i want to know how can i check the checkbox value & other field value with database value while submitting data to database.
following code i use to generate all selected items and then save too db
foreach ($this->addattendee->results as $key=>$value)
{
//print_r($value);
$id = $this->Attendee_model->save($value);
}
i am using codeigniter....can any one give the idea with sample code plz
{
$person = $this->Person_model->get_by_id($id)->row();
$this->form_data->id = $person->tab_classid;
$this->form_data->classtitle = $person->tab_classtitle;
$this->form_data->classdate = $person->tab_classtime;
$this->form_data->createddate = $person->tab_crtdate;
$this->form_data->peremail = $person->tab_pemail;
$this->form_data->duration = $person->tab_classduration;
//Show User Grid - Attendee>>>>>>>>>>>>>>>>>>>>>>>>
$uri_segment = 0;
$offset = $this->uri->segment($uri_segment);
$users = $this->User_model->get_paged_list($this->limit, $offset)->result();
// generate pagination
$this->load->library('pagination');
$config['base_url'] = site_url('person/index/');
$config['total_rows'] = $this->User_model->count_all();
$config['per_page'] = $this->limit;
$config['uri_segment'] = $uri_segment;
$this->pagination->initialize($config);
$data['pagination'] = $this->pagination->create_links();
// generate table data
$this->load->library('table');
$this->table->set_empty(" ");
$this->table->set_heading('Check', 'User Id','User Name', 'Email', 'Language');
$i = 0 + $offset;
foreach ($users as $user)
{
$checkarray=array('name'=>'chkclsid[]','id'=>'chkclsid','value'=>$user->user_id);
$this->table->add_row(form_checkbox($checkarray), $user->user_id, $user->user_name, $user->user_email,$user->user_language
/*,anchor('person/view/'.$user->user_id,'view',array('class'=>'view')).' '.
anchor('person/update/'.$user->user_id,'update',array('class'=>'update')).' '.
anchor('person/showattendee/'.$user->user_id,'Attendee',array('class'=>'attendee')).' '.
anchor('person/delete/'.$user->user_id,'delete',array('class'=>'delete','onclick'=>"return confirm('Are you sure want to delete this person?')"))*/ );
}
$data['table'] = $this->table->generate();
//end grid code
// load view
// set common properties
$data['title'] = 'Assign Attendees';
$msg = '';
$data['message'] = $msg;
$data['action'] = site_url('person/CreateAttendees');
//$data['value'] = "sssssssssssssssssss";
$session_data = $this->session->userdata('logged_in');
$data['username'] = "<p>Welcome:"." ".$session_data['username']. " | " . anchor('home/logout', 'Logout')." | ". "Userid :"." ".$session_data['id']; "</p>";
$data['link_back'] = anchor('person/index/','Back to list of Classes',array('class'=>'back'));
$this->load->view('common/header',$data);
$this->load->view('adminmenu');
$this->load->view('addattendee_v', $data);
}
The code is quite messy but I have solved a similar issue in my application I think, I am not sure if its the best way, but it works.
function save_vote($vote,$show_id, $stats){
// Check if new vote
$this->db->from('show_ratings')
->where('user_id', $user_id)
->where('show_id', $show_id);
$rs = $this->db->get();
$user_vote = $rs->row_array();
// Here we are check if that entry exists
if ($rs->num_rows() == '0' ){
// Its a new vote so insert data
$this->db->insert('show_ratings', $rate);
}else{
// Its a not new vote, so we update the DB. I also added a UNIQUE KEY to my database for the user_id and show_id fields in the show_ratings table. So There is that extra protection.
$this->db->query('INSERT INTO `show_ratings` (`user_id`,`show_id`,`score`) VALUES (?,?,?) ON DUPLICATE KEY UPDATE `score`=?;', array($user_id, $show_id, $vote, $vote));
return $update;
}
}
I hope this code snippet gives you some idea of what to do.
maybe i have same trouble with you.
and this is what i did.
<?php
public function set_news(){
$this->load->helper('url');
$slug = url_title($this->input->post('title'), 'dash', TRUE);
$query = $this->db->query("select slug from news where slug like '%$slug%'");
if($query->num_rows()>=1){
$jum = $query->num_rows() + 1;
$slug = $slug.'-'.$jum;
}
$data = array(
'title' => $this->input->post('title'),
'slug' => $slug,
'text' => $this->input->post('text')
);
return $this->db->insert('news', $data);
}
?>
then it works.

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;

How to display Serial Numbers in a table that has been created using table library in codeigniter?

I know how to create pagination and generate a table containing information from database in codeigniter, but I don't how to display the serial numbers for each row in the table. Example:
SL. Name Email
1. Srijon example#yahoo.com
2. Jake jake#yahoo.com
Would you please kindly show me how to do that? Thanks in advance
Here is the controller for how I create pagination and generate table (without serial numbers)
function index(){
$this->load->library('pagination');
$this->load->library('table');
$this->table->set_heading('Student ID','Student Name','Batch','Edit','Delete');
$config['base_url'] = 'http://localhost/coaching/index.php/student_list/index';
$config['total_rows'] = $this->db->get('student')->num_rows();
$config['per_page'] = 15;
$config['num_links'] = 20;
$config['full_tag_open'] = '<div id="pagination" align="center">';
$config['full_tag_close'] = '</div>';
$this->pagination->initialize($config);
$data['tab'] = "Student List";
$this->load->model('mod_studentlist');
$data['records']= $this->mod_studentlist->student_list();
$data['main_content']='studentlist';
$this->load->view('includes/template',$data);
}
Here's my model
function student_list()
{
$config['per_page'] = 10;
$this->db->select('studentid, studentname, batch');
$this->db->order_by("studentid", "desc");
$rows = $this->db->get('student',$config['per_page'],$this->uri->segment(3))->result_array();
foreach ($rows as $count => $row)
{
$rows[$count]['studentname'] = anchor('student_list/get/'.$row['studentid'],$row['studentname']);
$rows[$count]['Edit'] = anchor('update_student/update/'.$row['studentid'],'Update');
$rows[$count]['Delete'] = anchor('report/'.$row['studentid'],'Delete');
}
return $rows;
}
Here's my view file
<?php echo $this->table->generate($records);?>
<?php echo $this->pagination->create_links();?>
<script type="text/javascript" charset="utf-8">
$('tr:odd').css('background','#EAEAEA');
</script>
You should create a variable inside your model function:
<?php
function student_list()
{
$config['per_page'] = 10;
$this->db->select('studentid, studentname, batch');
$this->db->order_by("studentid", "desc");
$rows = $this->db->get('student',$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]['studentname'] = anchor('student_list/get/'.$row['studentid'],$row['studentname']);
$rows[$count]['Edit'] = anchor('update_student/update/'.$row['studentid'],'Update');
$rows[$count]['Delete'] = anchor('report/'.$row['studentid'],'Delete');
}
return $rows;
}
and modify your controller:
<?php
function index() {
$this->load->library('pagination');
$this->load->library('table');
$this->table->set_heading('SL.', 'Student ID','Student Name','Batch','Edit','Delete');
....
Codeigniter has a great Table library to display data in html table format. Adding a Serial No is sometime required to a table, but Row num is not easily provided by MySQL hence while using Table library this function is added to do the job.
Here goes the code:
/**
* Set the serial no
*
* Add serial no to left of table
*
* #access public
* #param mixed
* #return mixed
*/
function add_sr_no(&$arr)
{ if (!is_array($arr)) return $arr;
$i=1;
foreach ($arr as &$values) {
if (!is_array($values))
break;
else
array_unshift($values, $i++);
}
return $arr;
}
Just add these lines to table.php in library.
Usage:
$rows = $query->result_array();
$this->table->add_sr_no($rows);
Don't forget to add first column 'Sr No' in set_heading.
Read the post here.
Hope this helps.
Have you thought about doing this on the client? the javascript library datatables is brilliant. it can handle the sorting for you at the user side, and can be made to dynamically retrieve information using ajax, so load times are fast on large tables. for under < 100 rows or so there probably isn't a need though. i have it sorting/filtering tables with >100 000 rows with no problems at all (using ajax)
unless the serial numbers have semantic meaning don't show them to the client. it just more stuff for them to filter. if they are required for your code, but not for the user to see, just hide them away in a data attribute or something.

Resources