PHP 简单的分页的实现

做了一个简单的分页查询例子:

// 分页list
function getListByPage($category_id,$page){
	$pageSize = 10;	//每页大小
	$nums = 0;	//查询总数
	$allPage = 0;	//总的页数
	$index = $page;	//当前页数
	$start = $index * $pageSize;	//开始条目

	$isFirst = true;	//是否为第一页
	$isLast = true;		//是否为最后一页

	// 判断是否为第一页
	if((int)$index == 0){
		$isFirst = true;
	}else{
		$isFirst = false;
	}

	$conManager = new ConnetionManager();
	try{
		@$conn = $conManager -> getConn();
		// 查询总数
		$sql = "select count(*) from blog_article where category = '".$category_id."'";
		$result = mysqli_query($conn,$sql);
		$rows = mysqli_fetch_array($result);
		// 总数
		$nums = $rows[0];
		$allPage = ceil($nums/$pageSize);	//ceil()进一法取整函数

		// 判断是否为最后一页
		if( (int)$start+(int)$pageSize >= (int)$nums ){
			$isLast = true;
		}else{
			$isLast = false;
		}

		// 查询结果
		$sql = "select * from blog_article where category = '".$category_id."' limit ".$start.",".$pageSize;
		$result = mysqli_query($conn,$sql);
	}catch(Exception $e)
	{
		throw new Exception("Always throw this error");
		return true;
	}

	// 关闭连接
	$conn -> close();

	$list = array();
	while($row = mysqli_fetch_array($result)){
		$article = new Article($row['id'],$row['title'],$row['author'],$row['createtime'],"",$row['category'],$row['messages'],$row['visits']);
		array_push($list,$article);
	}

	$results = array("isFirst"=>$isFirst,"isLast"=>$isLast,"nums"=>$nums,"allPage"=>$allPage,"list"=>$list);

	return $results;

}

下面是前台代码:

<div class="pages">
	<?php 
		if($isFirst){ 
	?> 
		<a>首页</a> -- <a>上一页</a>
	<?php 
		}else{ 
	?>
		<a href="<?=root?>category_<?=$category_id?>_0.html">首页</a> --  
		<a href="<?=root?>category_<?=$category_id?>_<?=$page-1?>.html">上一页</a> 
	<?php 
		} 
	?>
	-- 	
	<?php 
			if($isLast){ 
		?> 
			<a>下一页</a> -- 
			<a >尾页</a>
		<?php
			}else{ 
		?> 
			<a href="<?=root?>category_<?=$category_id?>_<?=$page+1?>.html">下一页</a> 
			-- <a href="<?=root?>category_<?=$category_id?>_<?=$allPage-1?>.html">尾页</a>
			
		<?php 
			} 
		?> 
	-- 第<?=$page+1?>页/共<?=$allPage?>页
</div>

 

发表评论