php中一个可查询所有表的“通用”查询分页类
一个可查询所有表的“通用”查询分页类?最近突发奇想,希望写出一个可以针对所有表的查询分页类。因为在实际的开发中,恐怕查询并将结果集分页显示是用得最多的代码,而表的结构是多样的,我想尽可能地提高代码的重用率和维护性。?以下是我写的,请各位加以指点,测试,看能否进行更好的改进和更多的支持。?目前还只支持单一的表,不支持联合查询。但未来可以会考虑如何支持。?代码:?c_error.=没有连接上数据库。; exit; } $this->c_result=$connection; } //构造函数,初始化变量 function browser($tablename,$row,$sql,$lation,$orderby){ $this->c_table=$tablename; $this->c_rows=$row; if(empty($this->c_offset)){ $this->c_offset=0; } if (empty($tablename) or empty($row) or empty($sql)){ $this->c_error=没有查询的表或没有批定显示多少行或没有查询语句; } $this->c_query=$sql; if (!empty($lation)){ $this->c_query.= .$lation; } if (!empty($orderby)){ $this->c_query.= .$orderby; } } //计算总页数 function tatolpage(){ $sult=mysql_query(select count(*) as 'total_rows' from $this->c_table,$this->c_result); if ($sult==false) { $this->c_error.=计算结果集总数目的查询失败,请检查。; exit; } $tempvar=mysql_fetch_array($sult); $this->total=$tempvar[0]; } //查询得到结果集,存入数组c_found[][]中 function getfound(){ $sult=mysql_query($this->c_query,$this->c_result) or die(mysql_error()); while ($found=mysql_fetch_array($sult)){ $this->c_found[]=$found; } } //查询数据,并将结果分页存入一个变量 function showtable(){ $this->connect(); $this->tatolpage(); if (empty($_get[offset])){ $_get[offset]=0; } $this->c_query.= limit .$_get[offset]., .$this->c_rows; $sult=mysql_query($this->c_query,$this->c_result) or die(mysql_error()); //解析query,得到要显示出来的字段值 $tempvar=explode( ,$this->c_query); $fields=explode(,,$tempvar[1]); //字段值(数组) //显示数据到一个表 $echo_content.=
; while($found=@mysql_fetch_array($sult)){ $echo_content.=; $echo_content.=.$found[1]. ; //显示用户指定的字段,此处需仔细看 for($i=2;$i.$found[$i].; } $echo_content.=
; } //分页 if ($this->c_rows==0){ $this->c_error.=每页显示的数目不能为0; exit; } $total_page=ceil($this->total/$this->c_rows); $pre_page=$_get[offset]-$this->c_rows; //下一页 $nex_page=$_get[offset]+$this->c_rows; //显示上一页 if ($pre_page>=0){ $echo_content.=上页&; }else{ $echo_content.=
上页&; } //显示页码 for($i=1;$ic_rows==($i-1)){ $echo_content.=&第.$i.页&; }else{ $echo_content.=&c_rows.>.$i.&; } } //显示下一页 if ($nex_page!=0 and ($_get[offset]+$this->c_rows)total){ $echo_content.=&下页
; }else{ $echo_content.=&下页; } $echo_content.=
; return $echo_content; } } /*例子 //browser(表名,每页显示的数目,sql,查询条件,排序条件); $gggg=new browser(news,5,select auto_id,news_title from news,,order by newstime desc); $temp=$gggg->showtable(); echo $temp; //$gggg->getfound()是将查询结果集存在一个二维数组里,本例中没有用到。 */ ?>?