我在实现codeigniter分页类时遇到了困难。我已经创建了我的模型,视图和控制器,以获得我的新闻文章和数据成功地在视图中响应。
我的问题是,当我试图实现分页时,似乎我无法获得数据库中字段的正确计数。谁能告诉我我哪里做错了吗?
分页链接显示得很好,但显示的内容似乎没有受到限制。如何计算查询的行数?
自动加载分页所需的类
模型:
class News_model extends CI_model {
function get_allNews()
{
$query = $this->db->get('news');
foreach ($query->result() as $row) {
$data[] = array(
'category' => $row->category,
'title' => strip_tags($row->title),
'intro' => strip_tags($row->intro),
'content' => truncate(strip_tags( $row->content),200),
'tags' => $row->tags
);
}
return $data;
}
控制器 // load pagination class
$config['base_url'] = base_url().'/news/index/';
$config['total_rows'] = $this->db->get('news')->num_rows();
$config['per_page'] = '5';
$config['full_tag_open'] = '<div id="pagination">';
$config['full_tag_close'] = '</div>';
$this->pagination->initialize($config);
$viewdata['allnews'] = $this->News_model->get_allNews($config['per_page'],$this->uri->segment(3));
<<p> 视图/strong> <?php if (isset($allnews)): foreach ($allnews as $an): ?>
<?php echo heading($an['title'], 2); ?>
<?php echo $an['content']; ?>
<?php endforeach;
else: ?>
<h2>Unable to load data.</h2>
<?php endif; ?>
<?php echo $this->pagination->create_links(); ?>
在您的控制器中,您将参数传递给get_allNews方法,但您的方法没有使用这些参数:
$viewdata['allnews'] = $this->News_model->get_allNews($config['per_page'],$this->uri->segment(3));
所以你得到了所有的记录,并期望得到有限的结果集。您需要像这样更改get_allNews方法的开头:
class News_model extends CI_model {
// make use of the parameters (with defaults)
function get_allNews($limit = 10, $offset = 0)
{
// add the limit method in the chain with the given parameters
$query = $this->db->limit($limit, $offset)->get('news');
// ... rest of method below