2
votes

I am trying to use pagination for blog articles on my homepage:

Controller:

public function index()
{
   $data['view'] = "home";

    /** Pagination **/
    $config['base_url'] = base_url().'home/';
    $config['total_rows'] = $this->Blog_model->count_articles();
    $config['per_page'] = 2; 
    $config['uri_segment'] = 2;

    $this->pagination->initialize($config);

    $data['paginate'] = $this->pagination->create_links();
    $data['articles'] = $this->Blog_model->get_articles($config['per_page'],$this->uri->segment(2));

    $this->load->view('template', $data);

}

Everything seems to work ok with the information retrieval and the pagination however, when I click on the number links or next links I get a 404 Not Found error.

I am assuming that this has something to do with the URI segment?

The URL that is being loaded is http://www.example.com/home/2 for the second page.

3

3 Answers

4
votes

You can also add a routing rule like:

$route['home/(:num)'] = 'yourhomecontroller';

then you can use it without index or any method, the num tells it to route any url with a number after home/ to index of home

2
votes

Codeigniter pages are of the form http://domain.com/controller/method/arguments.
If you leave out the method the default one will load, but if you need to pass an argument, you'll have to put the method as it comes before.

 http://www.example.com/home/index/2
0
votes

controller code

public function index()
{

$home=$this->uri->segment(2);

$limit_ti=2;
if(!$home):
offset_ti = 0;
else:
$offset_ti = $home;
endif;


$this->load->model('Blog_model');// call model
$this->load->library('pagination'); // call library

$query=$this->Blog_model->get_articles($limit_ti,$offset_ti); // geting aan article 

$total_page = $this->Blog_model->count_articles(); // count row

 /** Pagination **/
 $config['base_url'] = base_url().'index.php/home/'; // assuming you doesn't have htaccess
 $config['total_rows'] =$total_page->num_rows();
 $config['per_page'] = 2; 
 $config['uri_segment'] = 2;

    $this->pagination->initialize($config);
    $data = array('query' => $query,'page'=>$home);

    $data['view'] = "home";
    $this->load->view('template', $data);

}

model code

function get_articles($limit,$ofset){
$query=$this->db->query("select * from *table* order by id ASC LIMIT $ofset,$limit");
return $query;
}

function count_articles(){
$query=$this->db->query("select * from table");
return $query;
}

in view

<?php echo $this->pagination->create_links(); // call the pagnation?>