數據分頁顯示的簡單實現

說明:
分頁顯示是通過SQL語句中的limit來實現,下面是我對分頁進行簡單的封裝

define("HOST",'localhost');
define("USERNAME",'root');
define("PWD",'');
define("DB_NAME",'');
define("CHARSET",'UTF8');
class Page
{
    private $link;//數據庫連接
    private $pages;//數據顯示所需總頁數
    private $num;//每頁顯示數據條數

    function __construct($num){//連接數據庫
        $this->num=$num;
        $link = mysqli_connect(HOST,USERNAME,PWD);
        if(!$link){
            exit('連接失敗,errno:'.mysqli_connect_errno().' error:'.mysqli_connect_error());
        }
        if(!mysqli_select_db($link,DB_NAME)){
            exit('數據庫指定失敗,errno:'.mysqli_errno($link).' error:'.mysqli_error($link));
        }
        if(!mysqli_set_charset($link,CHARSET)){
            exit('字符集設置失敗,errno:'.mysqli_errno($link).' error:'.mysqli_error($link));
        }
        $sql = 'select id from user';
        $res = mysqli_query($link,$sql);
        $this->pages = ceil(mysqli_num_rows($res)/$this->num);//求出所需頁數
        mysqli_free_result($res);
        $this->link=$link;
    }


    function showPages(){//顯示頁碼
        $p=1;//第幾頁
        echo '<a href="?p=1">首頁</a>  ';
        while($p<=$this->pages){
            echo '<a href="?p='. $p .'">'. $p .'</a>  ';
            $p++;
        }
        echo '<a href="?p='. $this->pages .'">尾頁</a>  ';
    }
    function getPage(){
        if(empty($_GET['p'])){//因爲首次進入本頁面不存在p的值,因此需要指定p的值,默認爲第一頁
            $_GET['p']=1;
            $p=$_GET['p'];
        }else{
            $p=$_GET['p'];
        }
        return $p;
    }
    function showTable($sql='select * from user'){//顯示數據,可以自己定義sql語句
        $p=$this->getPage();
        echo '<table border="1" width="800" align="center">';
        $sql = $sql.' limit '.($p-1)*$this->num .','. $this->num;
        $result = mysqli_query($this->link,$sql);
        if($result && mysqli_num_rows($result)){
            $flag=true;
            while($row  = mysqli_fetch_assoc($result)){
                if($flag){//顯示字段名字
                    echo '<tr>';
                        foreach($row as $key=>$val){
                            echo '<th>'.$key.'</th>';
                        }
                    echo '</tr>';
                    $flag=false;
                }
                echo '<tr>';
                foreach($row as $val){//輸出具體數據
                    echo '<td>'.$val.'</td>';
                }
                echo '</tr>';
            }
            echo '</table>';
        }else{
            echo 'sql執行錯誤,請檢查你的sql語句 '.$sql;
        }
        mysqli_free_result($result);
    }

    function __destruct(){
        mysqli_close($this->link);
    }
}

/*測試*/

$page = new Page(8);//表示每頁顯示8條數據
$sql = 'select username,email,reg_time from user';
$page->showTable($sql);

$page->showPages();
發佈了26 篇原創文章 · 獲贊 2 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章