links in pagination in codeigniter - codeigniter

in my view page,in the 1st form i have 2 select drop down...in the 1st drop down i am populating the value default from the controller...when u onchange the value in the 1st drop down,the selected value is passed to controller via javascript..in the controller,i get that 1st drop down value and load model and get value from model for the 2nd drop down and post it to view page...when u select the 2nd drop down value and click submit,the both drop down values are posted to controller after form validation and load model and get user information from the database and post it back again to view page ...this is the scenario for my view page..so,u can change the above both select drop down to get informations in the 2nd form in the same view page..now when i did pagination for my 2nd form user information,i am getting the links and data perfectly according to the limits and offsets..but,i am unable to retrieve the information when i click 2nd,3rd,4th..and rest on links while the informations are being posted from controller..so what can i do now?,,here is my code after i get both drop down values in the controller..
in my controller..
public function get_form_dept()
{
$this->load->helper(array('form', 'url'));
$this->load->library("pagination");
$this->load->library('form_validation');
$this->form_validation->set_rules('formation','Formation','required|required');
if($this->form_validation->run()== false) {
$this->viewstudent();
} else {
$config['base_url'] = base_url() . 'Incite/get_form_dept';
if($this->input->post('formation') == 1 && $this->input->post('department') == 1){
$config['total_rows'] = $this->db->get('user')->num_rows();
} else {
//$this->db->select('list_formation');
$query = $this->db->get_where('formation',array('id' => $this->input->post('formation')));
// echo $this->db->get_where('formation',array('id' => $this->input->post('formation')));
$row = $query->result();
foreach($row as $key) {
$get_formation = $key->list_formation;
echo $get_formation ."<br>";
}
$query1 = $this->db->get_where('department',array('id' => $this->input->post('department')));
$row1=$query1->result();
foreach($row1 as $key) {
$get_dept=$key->list_department;
echo $get_dept . "<br>";
}
//$array = array('formation' => $get_formation, 'department' => $get_dept);
//$config['total_rows']=$this->db->get('user',$array)->num_rows();
$query = $this->db->query("SELECT * FROM user where formation='$get_formation' and department='$get_dept'");
echo "SELECT * FROM user where formation='$get_formation' and department='$get_dept'" . "<br>";
$config['total_rows']=$query->num_rows();
//echo $row ."<br>";
//echo $row=$this->db->get('user',$array)->num_rows();
}
$config['per_page'] = 5;
//$config['uri_segment'] = 3;
//$choice = $config['total_rows'] / $config['per_page'];
// $config['num_links'] = round($choice);
$config['num_links'] = 2;
//$config['use_page_numbers'] = TRUE;
$config['suffix']= '?' . http_build_query($_GET, '', "&");
$this->pagination->initialize($config);
if($this->input->post('formation')== 1 && $this->input->post('department') == 1) {
// $this->db->limit($limit, $start);
$query_result = $this->db->get('user',$config['per_page'], $this->uri->segment(3));
$data['result']= $query_result->result();
} else {
$query = $this->db->get_where('formation',array('id' => $this->input->post('formation')));
$row = $query->result();
foreach($row as $key) {
$get_formation = $key->list_formation;
}
$this->db->where('id', $this->input->post('department'));
$query1 = $this->db->get('department');
$row1=$query1->result();
foreach($row1 as $key) {
$get_dept=$key->list_department;
//echo $get_dept;
}
$array = array('formation' => $get_formation, 'department' => $get_dept);
//$this->db->limit($limit, $start);
//$query = $this->db->get_where('user',$array);
$query_result=$this->db->get_where('user',$array,$config['per_page'], $this->uri->segment(3));
$data['result'] = $query_result->result();
}
$this->load->model('model_select_formation');
$data['formation'] = $this->model_select_formation->modelselectformation();
// query to fetch department
$data['dept']=$this->model_select_formation->get_department($data['formation_id']);
$data['formationid'] = $this->input->post('formation');
$data['departmentid'] = $this->input->post('department');
$this->load->view('viewstudent',$data);
}
}

Related

ci pagination shows same pages on all links

I am having the pagination kept in my codeigniter project. The links are all shown in the view page. But whichever link that I clicked is getting me to the same page...
The following is my controller code..
public function newsletter()
{
$this->load->library('pagination');
$config = array();
$config["base_url"] = base_url() . "index.php/welcome/newsletter";
$this->load->model('newsletter_model');
$total_row = $this->newsletter_model->record_count();
$config["total_rows"] = $total_row;
$config["per_page"] = 1;
$config['use_page_numbers'] = TRUE;
$config['num_links'] = $total_row;
$config['cur_tag_open'] = ' <a class="current">';
$config['cur_tag_close'] = '</a>';
$config['next_link'] = 'Next';
$config['prev_link'] = 'Previous';
$this->pagination->initialize($config);
if($this->uri->segment(3)){
$page = ($this->uri->segment(3)) ;
}
else{
$page = 1;
}
$this->load->model('newsletter_model');
$data["results"] = $this->newsletter_model->fetch_data($config["per_page"], $page);
$str_links = $this->pagination->create_links();
$data["links"] = explode(' ',$str_links );
$this->load->model('newsletter_model');
$data['rm_newsletter'] = $this->newsletter_model->get_rm_newsletter();
$this->load->view('newsletter/newsletter',$data);
}
The following is my view code:
foreach ($lt_newsletter as $letter) {
echo $newsletter['nl_newsletter']; }
<div id="pagination">
<ul class="pagination">
<?php foreach ($links as $link)
{
echo "<li>". $link."</li>";
} ?>
</ul>
</div>
And finally in my model:
public function fetch_data($limit, $id)
{
$this->db->limit($limit);
$this->db->where('nl_id', $id);
$query = $this->db->get("ins_newsletter");
if ($query->num_rows() > 0)
{
foreach ($query->result() as $row)
{
$data[] = $row;
}
}
}
public function record_count()
{
return $this->db->count_all("ins_newsletter");
}
public function get_rm_newsletter()
{
$data = $this->db->query('SELECT nl.* FROM ins_newsletter nl ORDER BY nl.nl_id DESC');
return $data->result_array();
}
In my browser all the links(1,2,3,4) are shown clearly, but after I click on every link(1,2,3,4), it is showing the same page with all the records. For presently, I have 4 records in my database and it lists all. Kindly point me where am i going wrong...! Thanks in Advance.
Maybe the error is in your model, I see that you have a
$this->db->where('nl_id', $id);
but in the function in the controller you pass two parameters
$data["results"] = $this->newsletter_model->fetch_data($config["per_page"], $page);
this are the pagination values, one for quantity of record,(not variable), and the other for the page you are passing (1,2,3,etc.)
So, you have to add another parameter to make the where. See this link in pagination does not work and if you have some other problem can tell me.

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.

Passing Two Arrays to View

OK, below is a get_members function in my controller that I pulled and manipulated from the interwebs... i can print out the information from $output in the controller, but I don't want to do that... I cannot figure out how to get it to be part of my view so I can list info from it freely...
I know it has something to do with the $data array in the index function... can anyone assist?
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Phonedirectory extends CI_Controller {
function get_members($group=FALSE,$inclusive=FALSE) {
// Active Directory server
$ldap_host = "fps";
// Active Directory DN
$ldap_dn = "OU=Users,DC=xxx,DC=org";
// User attributes we want to keep
$keep = array(
"samaccountname",
"displayName",
"telephonenumber"
);
// Connect to AD
$ldap = ldap_connect($ldap_host) or die("Could not connect to LDAP");
ldap_set_option ($ldap, LDAP_OPT_REFERRALS, 0);
ldap_set_option($ldap, LDAP_OPT_PROTOCOL_VERSION, 3);
ldap_bind($ldap, "CN=LDAP Reader,OU=Users - Special,DC=xxx,DC=org", "xxx") or die("Could not bind to LDAP");
// Begin building query
if($group) $query = "(&"; else $query = "";
$query .= "(&(objectClass=user)(objectCategory=person))";
// Filter by memberOf, if group is set
if(is_array($group)) {
// Looking for a members amongst multiple groups
if($inclusive) {
// Inclusive - get users that are in any of the groups
// Add OR operator
$query .= "(|";
} else {
// Exclusive - only get users that are in all of the groups
// Add AND operator
$query .= "(&";
}
// Append each group
foreach($group as $g) $query .= "(memberOf=OU=$g,$ldap_dn)";
$query .= ")";
} elseif($group) {
// Just looking for membership of one group
$query .= "(memberOf=OU=$group,$ldap_dn)";
}
// Close query
if($group) $query .= ")"; else $query .= "";
// Uncomment to output queries onto page for debugging
// print_r($query);
// Search AD
$results = ldap_search($ldap,$ldap_dn,$query);
$entries = ldap_get_entries($ldap, $results);
// Remove first entry (it's always blank)
array_shift($entries);
$output = array(); // Declare the output array
$i = 0; // Counter
// Build output array
foreach($entries as $u) {
foreach($keep as $x) {
// Check for attribute
if(isset($u[$x][0])) $attrval = $u[$x][0]; else $attrval = NULL;
// Append attribute to output array
$output[$i][$x] = $attrval;
}
$i++;
}
return $output;
}
public function index() {
$data = array('title' => 'Phone Directory', 'main_content' => 'pages/phoneDirectory');
$this->load->view('template/main', $data);
}
}
Correct me if I'm wrong, but it sounds like you just want the output sent to the view?
If that's the case, then add this to the index function
public function index() {
$data = array('title' => 'Phone Directory', 'main_content' => 'pages/phoneDirectory');
$data['members'] = $this->get_members();
$this->load->view('template/main', $data);
}
or however you want to append that to your data array.
Then in the view you can do:
<?php echo print_r($members, TRUE); ?>

codeigniter pagination error 404

I have Admin controller in codeigniter
class Admin extends CI_Controller {
function __construct() {
parent::__construct();
if (!$this->tank_auth->is_logged_in()) redirect('login');
$this->load->library('pagination');
}
function index() {
$offset = $this->uri->segment(2);
$config['per_page'] = 3;
$data['sitetitle'] = 'Výpis jobů';
$data['listings'] = $this->Jobs_model->get_listings(0,$user_id = FALSE,$config['per_page'],$offset);
$config['uri_segment'] = 2;
$config['base_url'] = base_url().'admin/';
$config['total_rows'] = $this->db->count_all_results('jobs');
$this->pagination->initialize($config);
$this->template->set('title', 'Domovská stránka');
$this->template->load('template', 'site', $data);
}
}
and Jobs_model
function get_listings($category, $user_id = false, $limit = 0, $offset = 0) {
$data = array();
$this->db->order_by('id', 'desc');
$q = $this->db->get('jobs');
if ($category) {
$options = array('category' => $category);
$this->db->order_by('id', 'desc');
$this->db->where('category', $category);
$q = $this->db->get('jobs', $limit, $offset);
}
else {
$query = $this->db->order_by('id', 'desc');
if ($user_id) $query = $query->where('user_id', $user_id);
$q = $query->get('jobs',$limit, $offset);
}
if ($q->num_rows() > 0) {
foreach ($q->result_array() as $row) {
$data[] = $row;
}
}
$q->free_result();
return $data;
}
first page in paginatiom obtain data, but links generating in pagination localhost/sitename/admin/3 produce 404 error.
Where is problem in my script
You need to change:
$config['base_url'] = base_url().'admin/';
To:
$config['base_url'] = base_url().'admin/index/';
If you need the url to be like admin/3, you can use a route or _remap.
Side note: consider using this to get your page number rather than the URI class:
function index($offset = 0) {
// your code
}
It will do the same thing, but it's convenient to use the controller method arguments when possible.
You need to do some change.
$config['base_url']=base_url().'admin/index';
change
$config['uri_segment'] = 3;
check if you are using .htaccess or not. If you aren't, then $config['base_url'] in above should be
$config['base_url']=base_url().'index.php/admin/index';
If you get 404 error on codigniter paggination please check follwing things :
1 ) Check your controller it's index or somthing else if it's index then base_url should be :
base_url().'admin/index/pages' and if it's somethings else it should be :
base_url().'admin/somethingelse/pages'
2 ) Check 'uri_segment' by $this->uri->segment(4) so by this you got the page number then else will do the codiegniter.

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.

Resources