1

我在实现 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));

看法

  <?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(); ?>
4

1 回答 1

2

在您的控制器中,您将参数传递给 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
于 2011-11-01T13:07:06.873 回答