Pagination links in codeigniter 2 went to empty result - php

I tried to create pagination in search result. I got whole search result and correct number of pagination links, but when tried to go to next page search result went blank. 1st page should be fine. But it dosen't shows any error.
Here is the code:
Controller function
public function staffsearch() {
if ($this->session->userdata('logged_in') == FALSE) {
$this->index();
} else {
$data['action'] = site_url('user/staffsearch/');
$search_by = $this->input->post('search_by');
$keyword = $this->input->post('keyword');
if (!empty($search_by) && !empty($keyword)) {
$uri_segment = 3;
$offset = $this->uri->segment($uri_segment);
$staff_details = $this->User_Model->get_staff_search_result($search_by, $keyword, $this->limit, $offset)->result();
$query = $this->db->query("SELECT * FROM `staff` WHERE `" . $search_by . "` LIKE '%" . $keyword . "%'");
$count = $query->num_rows();
$this->load->library('pagination');
$config['base_url'] = site_url('user/staffsearch/');
$config['total_rows'] = $count;
$config['per_page'] = $this->limit;
$config['uri_segment'] = $uri_segment;
$this->pagination->initialize($config);
$data['pagination'] = $this->pagination->create_links();
//$staff_details = $this->User_Model->get_staff_search_result($search_by, $keyword)->result();
$this->load->library('table');
$this->table->set_empty(' ');
$this->table->set_heading('S/No', 'Image', 'Name', 'Office', 'Phone');
$i = 0;
foreach ($staff_details as $staff) {
if ($staff->Office) {
$id = $staff->Office;
$staff_office = $this->User_Model->get_office_by_id($id)->row();
$office = $staff_office->building . ' ' . $staff_office->level . '-' . $staff_office->unit;
} else {
$office = '';
}
if ($staff->Photo_small == '') {
$pic = 'unavailable.jpg';
} else {
$pic = $staff->Photo_small;
}
$this->table->add_row(++$i, '<image src="' . base_url() . 'people/' . $pic . '" width="50" height="50">', anchor('user/staffdetails/' . $staff->people_id, $staff->Name), $office, $staff->Phone);
}
$data['title'] = 'Search Result';
$data['table'] = $this->table->generate();
}
$this->load->view('search_staff', $data);
}
}
Model function:
function get_staff_search_result($fiels, $key,$limit = 10, $offset = 0) {
if ($fiels == 'Name') {
$this->db->like('Name', $key);
} elseif ($fiels == 'Staffnumber') {
$this->db->like('Name', $key);
} else {
$this->db->like('Appointment', $key);
}
$this->db->order_by('Name', 'asc');
return $this->db->get($this->tbl_staff,$limit, $offset);
}
View:
<div>
<h2><?php if (isset($title)) { echo $title;} ?></h2>
<?php if (isset($table)) { echo $table; } ?>
<?php if (isset($pagination)) { echo $pagination;} ?>
</div>

The links created by the pagination class won't contain the 'search_by' and 'keyword' criteria and they certainly won't be in the post variables as when you click a page link you are doing an HTTP GET.
You need to think about either storing the criteria in somewhere like the user's session so that it can be reused for each page request or look to use the Pagination library from CodeIgniter 3 which supports adding items (such as your two search terms) as query string parameters which you could then also check for.
Details about the CodeIgniter 3 Pagination class can be found here.
Not tried this myself but you should also be able to amend the URL for the pagination links so they read:
site_url('user/staffsearch/') . $search_by .'/' . $keyword;
You could then read the individual URL segments to retrieve the search terms.

Related

Search function doesn't show anything

I'm trying for a search function, I made a public function in a file called Topic, and I tried calling the method in the index.php, however it doesn't show anything, I think the problem lies with the while statement, but i'm not entirely sure.
Topic.php
class Topic{
public function searchPosts($postTags)
{
$conn = Db::getInstance();
$statementSearch = $conn->prepare("SELECT * FROM topics INNER JOIN posttopic ON topics.topicID=posttopic.topicID INNER JOIN posts ON posttopic.postID=posts.postID WHERE naam = :naam");
$statementSearch->bindValue(":naam", $postTags);
return $statementSearch->execute(array());
}
}
Index.php
spl_autoload_register(function ($class) {
include_once("classes/" . $class . ".php");
});
$_SESSION['KEYWORD'] = array();
$postArray = array();
//$allResults2 = array();
if (isset($_POST['Find'])) {
if (!empty($_POST['Find'])) {
$searchTopic = new Topic();
$postTags = $_POST['naam'];
$searchTopic->searchPosts($postTags);
while ($row = $statementSearch->fetch(PDO::FETCH_ASSOC)) {
$_SESSION['KEYWORD'][] = $row['postImageUrl'];
$postArray[] = $row['postID'];
}
}
if (count($_SESSION['KEYWORD']) === 0) {
$error = "Sorry no results!";
}
}
This is the html where it should be printed.
<?php
foreach (array_combine($_SESSION['KEYWORD'], $postArray) as $imageLink => $i) {
echo "<a href='./pin.php?postid=$i' ><img src='" . $imageLink . "'</a>";
}
?>

Codeigniter- Pagination-showing empty data after delete/edit

I am listing the registered employee from the db and showing 10 employee per page. I'm using codeigniter pagination for the purpose.
If I deleted an employee in page 2, after deleting I need to go to page 2 showing rest of the employees in page 2.
View:
<a href="<?php echo $path;?>welcome/delete_employee/employeeid/<?php echo $row->empID;?>/pageNum/<?php echo $currentPage; ?>" onClick="return delAlert()";><img src="<?php echo $path;?>/img/delete.png" height="30px" width="30px" /></a>
Controller:
public function delete_employee()
{
$session_id = $this->session->userdata('logged_in');
if($session_id) {
$array = $this->uri->uri_to_assoc(3);
$count=$array['pageNum']-1;
$i=$count*10;
$this->load->model('welcomemodel','m',true);
$this->m->deleteemployee($array['employeeid']);
$config = array();
$config["base_url"] = base_url() . "welcome/employee";
$config["total_rows"] =$this->m->employee_count();
$config["per_page"] = 10;
$config["uri_segment"] = $array['pageNum'];
$data['showData'] = $this->m->getEmployee($config["per_page"], $i);
$this->pagination->initialize($config);
$data["links"] = $this->pagination->create_links();
$data["currentPage"] =$array['pageNum'];
$this->load->view('header');
$this->load->view('employee',$data);
} else {
$this->load->view('session_expired');
}
}
Model:
public function deleteemployee($employeeid)
{
$this->db->where('empID',$employeeid);
$this->db->delete('employee');
return $this->db->affected_rows();
}
public function getEmployee($limit, $start)
{
$this->db->limit($limit, $start);
$this->db->select()
->from('employee')
->order_by('emp_fname');
$this->db->join('service', 'employee.serviceID = service.serviceID','left');
$query=$this->db->get();
return $query;
}
public function employee_count()
{
return $this->db->count_all("employee");
}
But now the pagination link shows first page's link,even though contents of second page is displayed....
model method
public function employee_count()
{
$result = $this->db->get('employee');
if ($result->num_rows() > 0) {
//employee record available
return true;
}
else
{
// employee record not available
return false;
}
}
View
<?php
$getData = $this->[your model name]->getEmployee($limit, $start);
?>
<?php if ($getData): ?>
//Your Pagination Part Here.....
<?php else: ?>
// else Nothing
<?php endif ?>

codeigniter pagination not work for particular user articles

My Pagination not work , In this case simple print users article to match the rc code of users its work perfectly url is ../project/article/user_article/?rc=4715422 , its work but pagintion url not print any article, pagination url is ../project/article/user_article/?rc=4715422/1,
here is my code: controller code is -
public function user_article()
{
$rc=$_GET['rc'];
$data['title'] = "User Article";
$config = array();
$config["base_url"] = base_url() . 'article/user_article/?rc='. $rc ;
$config["total_rows"] = $this->article_m->record_count_uarticles($_GET);
$config["per_page"] = 1;
$config["uri_segment"] = 3;
$this->pagination->initialize($config);
$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
$data["results"] = $this->article_m->fetch_result_uarticles($_GET, $config["per_page"], $page);
$data["links"] = $this->pagination->create_links();
if ($this->session->userdata ('is_logged_in')){
$data['profile']=$this->model_users->profilefetch();
$this->load->view('header',$data);
$this->load->view('user_article', $data);
$this->load->view('sfooter', $data);
} else {
redirect('signin');
}
}
and my modal is :
public function record_count_uarticles($rc) {
$query=$this->db->select('email,writer')->where('rc',$rc['rc'])->get('users');
$result=$query->result_array();
if ($query->num_rows() > 0) {
$row = $query->row_array();
$array = array ('email' => $row['email'], 'status' => '1');
return $this->db->where($array)->count_all_results("articles");
}
}
public function fetch_result_uarticles($rc, $limit, $start) {
$query=$this->db->select('email,writer')->where('rc',$rc['rc'])->get('users');
$result=$query->result_array();
if ($query->num_rows() > 0) {
$row = $query->row_array();
$this->db->limit($limit, $start);
$array = array ('u.email' => $row['email'], 'a.status' => '1', 'u.writer' => '1');
$query1=$this->db->select('a.id,title,a.status,description,image,a.email,tags,postdate,firstname,lastname,rc')->join('users u','u.email = a.email','left')->where($array)->order_by('a.id', 'DESC')->get('articles a');
if ($query1->num_rows() > 0) {
foreach ($query1->result() as $row) {
$data[] = $row;
}
return $data;
}
return false;
}
}
Check this code, pagination show properly, first page article print correctly but after click on pagination link then no article print in scnd page
This Link work but default link is not work , is there any query to change the url
../project/article/user_article/?rc=4715422/1 -- Default Link Not Work
../project/article/user_article/1/?rc=4715422 -- Custom Edited Link work

Switch Case issue with default value

I am running with some weird situation with Switch Case statement in PHP, where it is somehow ignoring the case and throwing default value. However this is not limited to the Switch Case only and happening with if else as well. So might be something wrong I am doing apart from conditional check.
I am using codeingiter and below I am posting all my code and helpers. I hope this would be enough information but let me know if you need any more information.
Helpers
// get employees
function get_employees(array $array = array())
{
$CI = get_instance();
return $CI->db->get_where('employees', $array)->result();
}
// get employee status from the `employment_status`
function get_employee_status($id)
{
$result = get_employees(array('id' => $id));
foreach ($result as $employee)
{
$status = $employee->employment_status;
}
return ($status !== '') ? $status : 'none';
}
// get employee status icon (based on status)
function get_employee_status_icon($id, $tooltip = TRUE)
{
$status = get_employee_status($id);
$get_icon = ($tooltip) ? 'rel="tooltip" title="' . ucwords(str_replace('_', ' ', $status)) . '"' : NULL;
switch ($status)
{
case 'active':
$status_icon = '<span class="glyphicon glyphicon-ok" ' . $get_icon . '></span>';
break;
case 'at_risK':
$status_icon = '<span class="glyphicon glyphicon-warning-sign" ' . $get_icon . '></span>';
break;
case 'attrition':
$status_icon = '<span class="glyphicon glyphicon-ban-circle" ' . $get_icon . '></span>';
break;
default:
$status_icon = '<span class="glyphicon glyphicon-exclamation-sign" ' . $get_icon . '></span>';
break;
}
return $status_icon;
}
Controller
public function employees()
{
$this->data['title'] = '<i class="fa fa-users"></i> ' . lang('emp_all');
$base_url = base_url() . 'admin/hr/employees';
$numbs = $this->employees_model->filter_count();
$total_rows = $numbs['count'];
$limit = get_option('per_page');
$page = ($this->uri->segment(4) !== FALSE) ? (int) $this->uri->segment(4) : 0;
get_pagination($base_url, $total_rows, $limit, 4, 2, TRUE);
$this->data['results'] = $this->employees_model->fetch_rows($limit, $page);
$this->data['links'] = $this->pagination->create_links();
$this->load->view('hr/employees/index', $this->data);
}
View file
// view file
foreach ($results as $employee):
do_print(get_employee_status($employee->id) . ' - ' .get_employee_status_icon($employee->id));
echo '<tr>';
...
echo '<td class="status-' . get_employee_status($employee->id) . '">' . get_employee_status_icon($employee->id) . '</td>';
...
echo '</tr>';
endforeach;
To clear things again: the code outputs the default value (icon) for the last case. It is ignoring the last case just only for the ICON and not for the tooltip or even th class
So how can I fix this where I can get output same as the case everywhere?
EDIT: --- Added output images and var_dump image
Please see the second last var_dump and output result to match the at_risk icon. Which is wrong
HTML Output
var_dump()
First of all you should correct your this function by properly initializing $status variable;
// get employee status from the `employment_status`
function get_employee_status($id)
{
$result = get_employees(array('id' => $id));
$status = '';
foreach ($result as $employee)
{
$status = $employee->employment_status;
}
return ($status !== '') ? $status : 'none';
}
Now, you should do var_dump of $status and see what you find in status variable value.

CodeIgniter Search Results Pagination

Well I've searched and searched all around but I still can't find a solution to my problem. I'm still new to php and codeigniter so maybe I missed the answer already but anyways, here's what I'm trying to do.
This is my Controller (c_index.php) - calls a search function and performs pagination on the resulting array.
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class C_index extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->model('m_search');
$this->load->library("pagination");
$this->load->library("table");
}
/** Index Page for this controller */
public function index()
{
if($this->session->userdata('logged_in')){
$this->load->view('v_user');
}
else{
$this->load->view('index');
}
}
public function search()
{
// start of search
$search_term = $this->input->post('word');
$books = $this->m_search->search_books($search_term);
// start of pagination
$config['base_url'] = "http://localhost/test/index.php/c_index/search";
$config['per_page'] = 5;
$config['num_links'] = 7;
$config['total_rows'] = count($books);
echo $config['total_rows'];
$this->pagination->initialize($config);
$data['query'] = array_slice($books,$this->uri->segment(3),$config['per_page']);
$this->load->view("index",$data);
}
}
Here's my view (index.php) - basically just displays the pagination result
<h3> Search Results </h3>
<!-- table -->
<table class="table table-condensed table-hover table-striped" id="result_table">
<tbody>
<?php
if(isset ($query)){
if(count($query)!=0){
foreach($query as $item){
echo "<tr><td>". $item['title'] ." by " .$item['author'] ."<br/></td></tr>";
}
echo $this->pagination->create_links();
}
else
{
echo "No results found for keyword ' ". $this->input->post('word')." ' .";
}
}
else
{
echo "Start a search by typing on the Search Bar";
}
?>
</tbody>
</table>
My model (m_search.php) - basically searches the database and returns an array of results.
<?php
class M_search extends CI_Model{
function search_books($search_term='default')
{
$filter = $this->input->post('filter');
//echo $filter;
if($filter == 'title')
{
//echo 'title';
$this->db->select('*');
$this->db->from('book');
$this->db->like('title',$search_term);
// Execute the query.
$query = $this->db->get();
return $query->result_array();
}else if($filter == 'author')
{
//echo 'author';
$this->db->select('*');
$this->db->from('book');
$this->db->like('author',$search_term);
// Execute the query.
$query = $this->db->get();
return $query->result_array();
}else if($filter == 'type')
{
//echo 'type';
$this->db->select('*');
$this->db->from('book');
$this->db->like('book_type',$search_term);
// Execute the query.
$query = $this->db->get();
return $query->result_array();
}else if($filter == 'status')
{
//echo 'status';
$this->db->select('*');
$this->db->from('book');
$this->db->like('book_status',$search_term);
// Execute the query.
$query = $this->db->get();
return $query->result_array();
}else
{
//echo 'all';
$this->db->select('*');
$this->db->from('book');
$this->db->like('book_status',$search_term);
$this->db->or_like('book_type',$search_term);
$this->db->or_like('author',$search_term);
$this->db->or_like('title',$search_term);
// Execute the query.
$query = $this->db->get();
return $query->result_array();
}
}
}
Now my problem is keeping the results for the pagination.
The first page is fine but whenever I click on a page link, the results on the table show the whole database and is not limited to my search results.
I've read somewhere that I need to use sessions to keep my search_term so that it works when I switch pages but I don't know where to put it.
Any advice or suggestions would be greatly appreciated. Thanks.
There are several of different ways to handle search and pagination depending on your needs. Based on your existing code, this is what I would do.
Change
$search_term = $this->input->post('word');
to
$search_term = ''; // default when no term in session or POST
if ($this->input->post('word'))
{
// use the term from POST and set it to session
$search_term = $this->input->post('word');
$this->session->set_userdata('search_term', $search_term);
}
elseif ($this->session->userdata('search_term'))
{
// if term is not in POST use existing term from session
$search_term = $this->session->userdata('search_term');
}
function search_books($search_term='default')
{
$filter = $this->input->post('filter');
//echo $filter;
if($filter == 'title')
{
$this->db->like('title',$search_term);
}
else if($filter == 'author')
{
$this->db->like('author',$search_term);
}
else if($filter == 'type')
{
$this->db->like('book_type',$search_term);
}
else if($filter == 'status')
{
$this->db->like('book_status',$search_term);
}
else
{
$this->db->like('book_status',$search_term);
$this->db->or_like('book_type',$search_term);
$this->db->or_like('author',$search_term);
$this->db->or_like('title',$search_term);
// Execute the query.
}
$query = $this->db->get('book');
return $query->result_array();
}
}
Just trying to lessen your Model code, if you don't want to use "session" and want to copy, paste link/url and get same result in your search then you should use uri class in your controller.
you can use following code in your controller all query string will show in pagination links.
$config['reuse_query_string']=TRUE;
for additional parameters in paging link you can un comment following 2 lines.
//$getData = array('s'=>$search);
//$config['suffix'] = '?'.http_build_query($getData,'',"&");
$this->pagination->initialize($config);
Try in this way in your Controller,
public function search()
{
$result=array();
if($this->session->userdata('login_id')!='')
{
$q = trim($this->input->get('q'));
if(strlen($q)>0)
{
$config['enable_query_strings']=TRUE;
$getData = array('q'=>$q);
$config['base_url'] = base_url().'admin/Product/search/';
$config['suffix'] = '?'.http_build_query($getData,'',"&");
$config['first_url'] = $config['base_url'].'?q='.$q;
$config["per_page"] = 10;
$config['use_page_numbers'] = TRUE;
$total_row = $this->Prod_model->search_record_count($q);
$config['total_rows']=$total_row;
$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';
if($this->uri->segment(3))
{
$page = $this->uri->segment(3);
}
else
{
$page = 1;
}
$result['search'] = $this->Prod_model->search($q,$config["per_page"],$page);
if(empty($result['search']))
{
echo "no data found";die;
}
else
{
$this->pagination->initialize($config);
$str_links = $this->pagination->create_links();
$result["links"] = explode(' ',$str_links);
$id=$this->session->userdata('login_id');
$result['user']=$this->Home_model->user_details($id);
$this->template->load('prod_table',$result);
}
}
else
{
echo "empty string";die;
}
}
else
{
redirect(base_url()."admin/");
}
}

Categories