|
class MY_page extends CI_Controller{
public function __construct(){
parent::__construct();
}
/*
* @package CodeIgniter
* @author ken
* @since Version 1.0
* @date 2015-11-19
*
* @path Codeigniter/application/libraries/MY_page - 文件路径
* @class MY_page - 类名
* @function page_func - 函数名
*
* @test_version CodeIgniter 2 - 在 CodeIgniter2 测试过
*/
/*
数据表
create table page(
id int(8) primary key auto_increment,
name char(20) default null
)ENGINE InnoDB default charset=utf8;
insert into page(name) values('name1');#写入10条记录
*/
#分页函数
public function page_func(){
$limit = 1;
$page_num = $this->input->get('page');
$page_num < 1 ? $page_num=1 : $page_num;#防止页码为0
$data['page_count'] = $page_count = ceil($this->db->count_all_results('page', TRUE) / $limit);#总页数
$page_num > $page_count ? $page_num=$page_count : $page_num;#防止页码大于总页码
$data['page_num'] = $page_num;
$offset = $limit * ($page_num-1);
$offset < 1 ? $offset = 0 : $offset;#防止偏移量计算结果为 0.
/*
*@Note:
*- mysql的limit 1,2 表示的是 起始点,记录条数
*- 而CI 的limit 1,2 表示的是 记录条数,起始点
*- 页面显示的记录条数的变化应该是 (传入的页面-1)*每页显示的记录条数
*/
$table = $this->db->get('page', $limit, $offset);
$data['table'] = $table->result_array();
$this->load->view('MY_page/test_page', $data);
}
}
//前端代码
/*
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title></title>
</head>
<body>
<table border='1' cellspacing="0" cellpadding="5">
<thead>
<tr>
<th>id</th>
<th>name</th>
</tr>
</thead>
<tbody>
<?php foreach($table as $vals): ?>
<tr>
<td><?=$vals['id'];?></td>
<td><?=$vals['name'];?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<p>
<a href='<?=base_url("index.php/my_page/page_func?page=1");?>'>首页</a>
<a href='<?php echo base_url("index.php/my_page/page_func?page=".($page_num-1 <1 ? $page_num=1 : $page_num-1)); ?>'>上一页</a>
<span><?=$page_num;?>/<?=$page_count;?></span>
<a href='<?php echo base_url("index.php/my_page/page_func?page=".($page_num+1 >$page_count ? $page_count : $page_num+1)); ?>'>下一页</a>
<a href='<?php echo base_url("index.php/my_page/page_func?page=".$page_count); ?>'>末页</a>
<input type='text' style='text-align: center;' size='5' id='jump_num' onchange='jump_url()' value=''>
<a id='jump_url' href=''>跳转</a>
</p>
<script type="text/javascript">
function jump_url()
{
var o_jump_num = document.getElementById('jump_num');
var o_jump_url = document.getElementById('jump_url');
var n_jump_num = parseInt(o_jump_num.value);
if(n_jump_num < 1){
n_jump_num = 1;
o_jump_url.href = 'http://'+location.hostname+'/index.php/my_page/page_func?page='+n_jump_num;
}else if(n_jump_num > <?=$page_count;?>){
n_jump_num = <?=$page_count;?>;
o_jump_url.href = 'http://'+location.hostname+'/index.php/my_page/page_func?page='+n_jump_num;
}else{
o_jump_url.href = 'http://'+location.hostname+'/index.php/my_page/page_func?page='+n_jump_num;
}
}
</script>
</body>
</html>
*/
|
|