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.=""; } $echo_content.=""; while($found=@mysql_fetch_array($sult)){ $echo_content.="| "; $echo_content.="".$found[1]." | "; //顯示使用者指定的欄位,此處需仔細看 for($i=2;$i
"; } //分頁 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;$i<=$total_page;$i++){ if ($_GET[offset]/$this->c_rows==($i-1)){ $echo_content.="&第".$i."頁&"; }else{ $echo_content.="&c_rows.">".$i."&"; } } //顯示下一頁 if ($nex_page!=0 and ($_GET[offset]+$this->c_rows)<=$this->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()是將查詢結果集存在一個二維數組裡,本例中沒有用到。 */ ?>?