将分页添加到用codeigniter编写的简单博客中

时间:2013-08-14 00:37:17

标签: codeigniter pagination blogs

我编写了一个带有codeigniter的简单数据库显示控制器,并尝试添加分页。控制器从数据库获取信息(它非常小,因此不需要模型)并将其发送到视图以显示分页。分页链接显示但由于某种原因未显示数据库信息。我一直收到这个错误: 资源ID#7资源ID#13

遇到PHP错误

严重性:注意

消息:数组到字符串转换

文件名:views / blog_view.php

行号:12

< ---数据库结构--->

CREATE TABLE `cities` (
`city` varchar(50) NOT NULL,
`state_code` char(2) NOT NULL,
 KEY `idx_state_code` (`state_code`)
 ) ENGINE=MyISAM;

< ---网站控制器--->

<?php
class Site extends CI_Controller {

public function index()
{
    $this->load->library('pagination');
    $this->load->library('table');
    $config['base_url'] =     'http://localhost:8888/pagination/index.php/site/index/';
    $config['total_rows'] = $this->db->get('cities')->num_rows();
    $config['per_page'] = 20;

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

    $data['records'] = $this->db->get('cities', $config['per_page'], $this->uri->segment(3));

    $this->load->view('data_view',$data);
 }
}
?>

&lt; --- data_view ---&gt;

<!DOCTYPE html>
<html>
<head>
<title>Display Database info</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- Bootstrap -->
<link href="css/bootstrap.min.css" rel="stylesheet" media="screen">
</head>
<body>

<?foreach($records as $item):?>
    <?php echo $item; ?>
<?endforeach?>

<?php echo $this->pagination->create_links(); ?>

<!-- Enable responsive features in IE8 with Respond.js (https://github.com/scottjehl/Respond) -->
<script src="js/respond.js"></script>
</body>

2 个答案:

答案 0 :(得分:0)

您需要在该查询上调用result()。

public function index()
{
    $this->load->library('pagination');
    $this->load->library('table');
    $config['base_url'] =     'http://localhost:8888/pagination/index.php/site/index/';
    $config['total_rows'] = $this->db->get('cities')->num_rows();
    $config['per_page'] = 20;

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

    $query = $this->db->get('cities', $config['per_page'], $this->uri->segment(3));
    $data['records'] = $query->result();

    $query->free_result();

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

答案 1 :(得分:0)

使用此更新的代码,您必须调用result()方法并指定字段名称。

<?foreach($records->result() as $item):?>
    <?php echo $item->city; ?>
<?endforeach?>