Search with Pagination in Codeingter
Step 1 : Created search_results.php in view
<?php include ('public_header.php');?>
<div class="container">
<h1>Serach Results</h1>
<table class="table">
<thead>
<tr>
<td>Sr No.</td>
<td>Article Title</td>
<td>Published On</td>
</tr>
</thead>
<tbody>
<tr>
<?php if(count($articles)):?>
<?php $count=$this->uri->segment(4,0);?>
<?php foreach($articles as $article ):?>
<td><?= ++$count?></td>
<td><?= $article->title?></td>
<td><?= "Date" ?></td>
</tr>
<?php endforeach;?>
<?php else: ?>
<tr>
<td colspan="3"> No Records Found.</td>
</tr>
<?php endif;?>
</tbody>
</table>
<?= $this->pagination->create_links();?>
</div>
<?php include ('public_footer.php');?>
step 2 created function in controller
public function search()
{
$this->load->library('form_validation');
$this->form_validation->set_rules('query','Query','required');
if(! $this->form_validation->run())
$this->index();
$query=$this->input->post('query');
return redirect("user/search_results/$query");
// $this->load->view('public/search_results',compact('articles'));
}
public function search_results($query)
{
$this->load->helper('form');
$this->load->model('articlesmodel','articles');
$this->load->library('pagination');
$config=[
'base_url' => base_url("user/search_results/$query"),
'per_page' => 5,
'total_row' => $this->articles->count_search_results($query),
'full_tag_open' => "<ul class='pagination'>",
'full_tag_close'=> "</ul>",
'first_tag_opne' => "<li>",
'first_tag_close'=> "</li>",
'uri_segment' => 4,
// 'first_link' => "<li>"
// 'last_link' => "</li>"
'last_tag_opne' => "<li>",
'last_tag_close' => "</li>",
'next_tag_opne' => "<li>",
'next_tag_close' => "</li>",
'pre_tag_open' => "<li>",
'pre_tag_close' => "</li>",
'num_tag_open' => '<li>',
'num_tag_close' => '</li>',
'cur_tag_open' => "<li class='active'><a>",
'cur_tag_close' => '</a></li>',
];
$this->pagination->initialize($config);
$articles=$this->articles->search($query,$config['per_page'],$this->uri->segment(4));
$this->load->view('public/search_results',compact('articles'));
}
Step 3 :Created function in model
public function search($query,$limit,$offset)
{
$q=$this->db->from('articles')
->like('title',$query)
->limit($limit,$offset)
->get();
return $q->result();
}
public function count_search_results($query)
{
$q=$this->db->from('articles')
->like('title',$query)
->get();
return $q->num_rows();
}