<?php
$pg = new pg;
//通用列表类
class pg {
	//页面判断
	function pn($allpage,$page) {
		$page=intval($page);
		if ($page>$allpage) $page=$allpage;
		if ($page<1) $page=1;
		return $page;
	}
	//简单列表
	function glist($sql,$total,$page=1,$per=20,$pagename='?page='){
		global $db;
		$allpage=ceil($total/$per);//总页数
		//返回正确的page
		$page=$this->pn($allpage,$page);
		$number = ($page-1)*$per;
		$return['list'] = $db->fetch_all("{$sql} limit {$number},{$per}");
		$return['listpage'] = $this -> Pager($allpage,$page,$pagename);
		return $return;
	}
	//id组合
	function ids($sql){
		global $db;
		$arr=$db->fetch_all($sql);
		$zt=array();
		foreach($arr as $v){
			$zt[]=$v[0];
		}
		$zt=implode(',',$zt);
		return $zt;
	}
	//读取列表
	function getlist($con=array()) {
		global $db;
		//初始化参数
		$what="*";
		$pri="ID";
		$where="";
		$orderby="";
		$per="20";
		$page="0";
		$pagename="?page=";
		$nopage=false;
		//读取参数
		foreach($con as $k=>$v){
			$$k=$v;
		}
		$total = $db->fetch_one("select count(*) from {$table} {$where}");
		$allpage=ceil($total/$per);
		//返回正确的page
		$page=$this->pn($allpage,$page);
		$number = ($page-1)*$per;
		//id组合
		$ids=$this->ids("select {$pri} from {$table} {$where} {$orderby} LIMIT {$number},{$per}");
		if (empty($ids)) {
			$zt=array();
		}else{
			$sql="select {$what} from {$table} where {$pri} in ($ids) {$orderby}";
			$zt = $db->fetch_all($sql); //获取全部记录
		}
		$return['list'] = $zt;
		$return['listall'] = $total;
		if ($nopage==false){
			$return['listpage'] = $this -> Pager($allpage,$page,$pagename);
		}
		return $return;
	}
	//分页
	function Pager($allpage,$page,$pagename,$ext=''){
		//总页数、当前页、页面前缀、页面后缀
		$page=$this->pn($allpage,$page);
		$next=$page+1;
		$pre=$page-1;
		$startcount=$page-5;
		$endcount=$page+5;
		if($startcount<=1) $startcount=1;
		if($endcount>=$allpage) $endcount=$allpage;
		//无分页
		if($allpage<=1)	{
			return '';
		}
		//分页开始
		$pageout='';
		if($page>1){
			$pageout .= "\n<a href=\"{$pagename}{$pre}{$ext}\">上一页</a> ";
			$pageout .= "\n<a href=\"{$pagename}1{$ext}\"><<</a> ";
		}
		for($i=$startcount;$i<=$endcount;$i++){
			if ($i==$page) {
				$pageout .= "\n<b style='padding:3px 6px;background:#ddd;'>{$i}</b> ";
			}else{
				$pageout .= "\n<a href=\"{$pagename}{$i}{$ext}\">{$i}</a> ";
			}
		}
		if($page<$allpage){
			$pageout .= "\n<a href=\"{$pagename}{$allpage}{$ext}\">>></a>";
			$pageout .= "\n<a href=\"{$pagename}{$next}{$ext}\">下一页</a> ";
		}
		return $pageout;
	}
}
?>