i make pagination but it cant limit post per page

2019-05-24 14:08发布

问题:

this is my controller , i use $config['per_page'] to limit my post but it not work still all my database show in it,

function index()

{

    $jumlah_data = $this->m_berita->jumlah_data();

    $config['base_url'] = base_url().'berita/index/';
    $config['total_rows'] = $jumlah_data;
    $config['per_page'] = 2;
    $from = $this->uri->segment(3);

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

    $halaman['berita'] = $this->m_berita->data($config['per_page'],$from);

    $urutan['berita'] = $this->db->order_by("id", "desc");

    $data['berita'] = $this->m_berita->data_berita()->result(); 

    $this->load->view('artikel', $data, $urutan, $halaman);     

}

my model

class m_berita extends CI_Model{

public function __construct()

    {
        $this->load->database();
    }

    public function data_berita(){
        return $this->db->get('berita');

    }

    public function data($number,$offset){
        return $query = $this->db->get('berita',$number,$offset)->result(); 
    }

    function jumlah_data(){
        return $this->db->get('berita')->num_rows();
    }

and this my view

    <?php 
$no = $this->uri->segment('3') + 1;
foreach ($berita as $u) { 
?>

<?php $no++;?>
<div class="container">
<?php $u->id; ?> 
    <h4> <?php echo $u->judul; ?> </h4>
    <span style="margin-bottom: 5%;" class="image left 3u"><img class="fit" src="<?php echo base_url('images/').$u->gambar; ?>" alt="" /></span>
    <?php $artikel = $u->isi; $artikel=word_limiter($artikel, 98); ?> <?php echo $artikel;?> <?php echo anchor('berita/tampil_berita/'.$u->id,'Read More'); ?>
</div>

<?php } ?>
<div class="container">
<ul class="pagination">
  <li><?php echo $this->pagination->create_links(); ?></li>
</ul>
</div>

回答1:

change the db function

to

function jumlah_data(){
    return $this->db->count_all('berita');
}


回答2:

Controller Code :

$this->load->library('pagination');

$config['base_url'] = 'base_url().'berita/index/';

$config['total_rows'] = $this->db->get('berita')->num_rows();

$config['next_link'] = 'Next';

$config['prev_link'] = 'Previous';

$config['uri_segment'] = 4;

$config['per_page'] = 10;

$config['num_links'] = 20;

$config['full_tag_open'] = '<div id="pagination" class="pagination">';

$config['full_tag_close'] = '</div>';

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

$this->data['berita'] = $this->m_berita->data_berita($config['per_page']);

Model Code :

function data_berita($per_page) {

        $query = $this->db->get('berita', $per_page, $this->uri->segment(3));

        return $query->result_array();

    }

View Code :

echo $this->pagination->create_links();

and then loop