728x90

PHP 에서 페이징 처리하는 방법이다.
Paging 이란 전체 자료를 가져오는 것이 아니라 일정한 갯수만큼 화면에 가져오도록 처리하는 로직이다.


1. 한 페이지에 보여줄 개수를 정한다.

2. DB에서 전체 자료수(total Rows)에서 총 페이지수를 구한다.

3. 실제 페이지 번호가 표시될 개수를 정한다. 보편적으로 10개씩 보여주도록 할 수 있다.

4. 첫페이지로 가는 버튼

5. 마지막 페이지로 가는 버튼

6. 이전 블록으로 가는 버튼

7. 다음 블록으로 가는 버튼

 

변수를 정의해보자.

1. $totalcnt : 총 게시물수

2. $rowsPage : 한 페이지에 보여줄 개수

3. $totalPage = ceil($totalcnt/$rowsPage); // 총 페이지수

    총페이지수가 0 이면 1로 표기

    if($totalPage == 0) {

          ++$totalPage;

    }

4. $total_block = ceil($totalPage / $block_limit); //전체 블록 갯수

5. $curPage = $curPage ? $curPage : 1; // 현재 페이지

6. $block_limit : 한 화면에 뿌려질 게시글 개수

7. $current_block=ceil($curPage/$block_limit); // 현재 블럭 : 화면에 표시될 페이지 리스트

8. $fstPage = (((ceil($curPage/$block_limit)-1)*$block_limit)+1); // 현재 블럭의 시작

9. $endPage = $fstPage + $block_limit -1; // 현재 블럭의 마지막

    if($totalPage < $endPage) {
        $endPage = $totalPage;
     }
10. $prev_page = $fstPage - 1; // 시작 바로 전 페이지

11. $next_page = $endPage + 1; // 마지막 다음 페이지

 

 

이제 본문에 뿌릴 개수를 함수로 만들어 보자.

<?php
class MySQLDbClass {

 

    function isConnectDb($db) {
        $conn = mysql_connect($db['host'].':'.$db['port'],$db['user'],$db['pass']);
        //Set encoding
        mysql_query("SET CHARSET utf8");
        mysql_query("SET NAMES 'utf8' COLLATE 'utf8_general_ci'");
        if(!$conn){
        die('Not connected :' . mysql_error());
        exit;
        }
        $selc = mysql_select_db($db['name'],$conn); // 접근한 계정으로 사용할 수 있는 DB 선택
        return $selc ? $conn : false;
    }

 

    //DB데이터 ARRAY -> 테이블에 출력할 데이터 배열
    // order by : 정렬 순서, rowsPage : 화면에 출력할 개수, curPage : 현재 페이지
    function getDbArray($table,$where,$flddata,$orderby,$rowsPage,$curPage){
        global $db;
        $curPage = $curPage ? $curPage : 1; // 현재 페이지가 없으면 1로 설정
        $sql = 'select '.$flddata.' from '.$table.($where?' where '.$this->getSqlFilter($where):'').($orderby?' order by '.$orderby:'').($rowsPage?' limit '.(($curPage-1)*$rowsPage).', '.$rowsPage:'');
        //echo $sql;
        $result = mysql_query($sql);
        return $result;
    }

    //SQL필터링
    function getSqlFilter($sql){
        return $sql;
    }

}//end dbClass

 

화면 하단에 뿌릴 페이징 처리 함수 만들기

dbClass 함수 안에 넣어도 되고 별도의 클래스를 만들어서 호출해서 사용해도 된다.

// $curPage : 현재 페이지, $totalcnt : 총 게시물수
// $block_limit : 한 화면에 뿌려질 게시글 개수
function PageList($totalcnt,$rowsPage,$curPage,$block_limit) {
    $block_limit = $block_limit ? $block_limit : 10;  // 한 화면에 보여줄 개수 기본 10으로 설정

    // 총 페이지수 구하기
    $totalPage = ceil($totalcnt/$rowsPage); 
    if($totalPage == 0) {
        ++$totalPage;
    }
    $total_block = ceil($totalPage / $block_limit); //전체 블록 갯수
   
    $curPage = $curPage ? $curPage : 1; // 현재 페이지

    // 현재 블럭 : 화면에 표시될 페이지 리스트
    $current_block=ceil($curPage/$block_limit);
    // 현재 블럭에서 시작페이지
    $fstPage = (((ceil($curPage/$block_limit)-1)*$block_limit)+1);
    // 현재 블럭에서 마지막 페이지
    $endPage = $fstPage + $block_limit -1;
    if($totalPage < $endPage) {
        $endPage = $totalPage;
    }

    // 시작 바로 전 페이지
    $prev_page = $fstPage - 1;
    // 마지막 다음 페이지
    $next_page = $endPage + 1;

    foreach(range($fstPage, $endPage) as $val) {
        $row[] = $val;
    }
    // 배열로 결과를 돌려준다.
    return array(
        'total_block' => $total_block,
        'current_block' => $current_block,
        'totalPage' => $totalPage,
        'fstPage' => $fstPage,
        'endPage' => $endPage,
        'prev' => $prev_page,
        'next' => $next_page,
        'current' => $row
    );
}

 

페이징 화면에 출력하기

HTML 문법은 bootstrap3 또는 bootstrap4에 맞게 Class만 수정해주면 된다.

function PageLinkView($link_url,$totalcnt,$rowsPage,$curPage){
    echo '<div style="position:relative;vertical-align:top;padding-top:0;margin-top:0">';
        echo "<span style='position:absolute;top:10px;'>[총 자료수:".$totalcnt."]</span>";
        echo '<div class="pagelink">';
            $Info = $this->PageList($totalcnt,$rowsPage,$curPage,'');
            if($Info['current_block'] > 2){
                echo "<a href='".$link_url."?p=1'>◀</a> ";
            }
            if($Info['current_block'] > 1){
                echo "<a href='".$link_url."?p=".$Info['prev']."'>◁</a> ";
            }
            foreach($Info['current'] as $w) {
                if($curPage == $w){
                    echo "<a href='".$link_url."?p=".$w."'><span style='color:red;font-size:22pt'>".$w."</span></a> ";
                } else {
                    echo "<a href='".$link_url."?p=".$w."'>".$w."</a> ";
                }
            }
            if($Info['current_block'] < ($Info['total_block'])){
                echo "<a href='".$link_url."?p=".$Info['next']."'>▷</a> ";
            }
            if($Info['current_block'] < ($Info['total_block']-1)){
                echo "<a href='".$link_url."?p=".$Info['totalPage']."'>▶</a> ";
            }
        echo '</div>';
    echo '</div>';
}   

 

사용법 예제

<?php
include_once 'dbinfo.php';
require_once 'phpclass/dbClass.php';

$conn = new MySQLDbClass(); // DB 함수
$db = $conn->isConnectDb($DB);

// 화면에 출력할 칼럼 발췌
$flddata ="(select name from cate where uid=d.cat1) as cat1,subject,content";
$rowsPage = 12;
$curPage = isset($_GET['p']) ? $_GET['p'] : 1;
$result = $conn->getDbArray('data d','',$flddata,'',$rowsPage,$curPage);
$totalcnt 구하는 함수 처리

 

본문 Layout : 테이블을 작성해서 $result 배열 결과물을 table td 태그안에 기록

페이징 Layout : 페이징 화면 출력

 

?>

 

함수로 만든 모든 것을 표기하지는 않았다.

이런 형태로 만들어 볼 수 있다는 것만 알 수 있게 작성했다.

 

실 사용 예제

- 네이버지식인에 링크를 걸어줬더니 성의없는 답변이라는 댓글을 보고서 실제 사용하는 예제를 추가했음.

- 어떻게 처리하는지에 대한 흐름만 이해하면 되는 사항.

<?php
if(!isset($_SESSION)) {
    session_start();
}
 
require_once '../dbconnect.php';
require_once '../phpclass/dbClass.php';
require_once '../phpclass/bbsClass.php';
require_once '../phpclass/adminClass.php';
$a = new adminClass();
$b = new bbsClass();
$c = new MySQLDbClass();
 
// 설문 테이블 상태 변경 체크
$a->surveyDBupdate();
 
$url = $_SERVER['PHP_SELF']; // 현재 실행중인 파일명 가져오기
$page = isset($_GET['page'])? trim($_GET['page']):1;//페이지 변수 설정
$rowsPage = 10// 한 화면에 표시되는 게시글 수
$curPage = isset($_GET['p']) ? $_GET['p'] : 1;
$bd_name = isset($_GET['bd_name']) ? $_GET['bd_name'] :'';
$mode = isset($_GET['mode']) ? $_GET['mode'] :'list';
$sel = isset($_GET['sel'])? $_GET['sel'] : '';
 
$flddata ="*";// 화면에 출력할 칼럼 발췌
$where = isset($_GET['where']) ? $_GET['where']: '';
$keyword = isset($_GET['keyword']) ? $_GET['keyword']: '';
$xorderbyisset($xorderby) ? $xorderby : 'uid DESC';
if($where && $keyword) {
    if($where == 'title'$sql = "title LIKE '%".$keyword."%' ";
    if($where == 'content'$sql = "content LIKE '%".$keyword."%' ";
    if($where == 'unify') {
        $sql = "(title LIKE '%".$keyword."%' OR content LIKE '%".$keyword."%') ";
    }
else {
    $sql ='';
}
if(!empty($sel)){
    if($keyword){
        $sql .= " and status = ".$sel;
    } else {
        $sql = " status = ".$sel;
    }
}
 
//echo $sql.'<br />';
 
$link_url=($bd_name?'bd_name='.$bd_name.'&amp;':'').($mode?'mode='.$mode.'&amp;':'').($sel?'sel='.$sel.'&amp;':'').($where?'where='.$where.'&amp;':'').($keyword?'keyword='.urlencode(stripslashes($keyword)).'&amp;':'');
$g['bbs_reset'= $url// 초기화
 
$table ='poll_admin';
$rows$c->getDbArray($table,$sql,$flddata,$xorderby,$rowsPage,$curPage);
$NUM = $c->getDbRows($table,$sql); // 전체 게시글수
$TPG = $b->getTotalPage($NUM,$rowsPage);
?>
 
<!DOCTYPE html>
<head>
<title><?php echo $title;?></title>
<meta charset="utf-8">
<meta name="robots" content="noindex,nofollow"/>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="../vendor/bootstrap/css/bootstrap.min.css">
<link href="vendor/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
<link href="https://fonts.googleapis.com/css?family=Montserrat:400,700" rel="stylesheet" type="text/css">
<link href="https://fonts.googleapis.com/css?family=Lato:400,700,400italic,700italic" rel="stylesheet" type="text/css">
<link rel="stylesheet" type="text/css" href="../css/survey.css" />
<script src="../vendor/jquery/jquery.min.js"></script>
<script src="../vendor/bootstrap/js/bootstrap.min.js"></script>
<script src="../js/modal.js"></script>
</head>
<body>
<div class="container">
<table class="table table-bordered">
<tr>
    <td align=center><font class='title'><b>설문조사<br><br>
    <div class="pull-left info bmargin">
        <select name='sel' onchange='document.searchf.sel.value=this.value;document.searchf.submit();'>
        <option value=''>전체목록보기</option>
        <option value='1' <?php if("1"==$sel):?> selected<?php endif?>>진행중목록</option>
        <option value='2' <?php if("2"==$sel):?> selected<?php endif?>>종료 목록</option>");
        </select>
    </div>
    <div class="pull-right info bmargin">
        <a href='survey_admin.php'><button class="w3-button w3-blue-grey w3-tiny">관리</button></a>&nbsp;
        <a href='add_form.php?mode=new'><button class="w3-button w3-blue-grey w3-tiny">등록</button></a>
    </div>
<!--  설문 내용 -->
<table class='w3-table w3-bordered'>
    <thead>
        <tr class="w3-blue-grey">
            <th width="8%">No</th>
            <th width="43%">설문 제목</th>
            <th width="11%">총응답</th>
            <th width="13%">시작일</th>
            <th width="13%">종료일</th>
            <th width="10%">상 태</th>
        </tr>
    </thead>
    <tbody>
        <?php $i=1;foreach($rows as $R):?>
        <tr>
            <td><?php echo $i;?></td>
            <td>
            <?php
                $memo="&nbsp;<a href='survey_memo.php?bd_name=".$R['bd_name']."&mode=list&sel=".$sel."'><img src='./image/memo.gif' border='0' alt='메모보기'></a>";
                if($R['enddate'< date("Y-m-d")){
                    echo "<a href='survey_res.php?bd_name=".$R['bd_name']."&sel=".$sel."'> ".$R['title']."</a>$memo</td>";
                    $status = "종 료";
                } else {
                    if($R['startdate'> date("Y-m-d")) $status = "준비중";
                    else $status = "진행중</td>";
                    echo "<a href='survey.php?bd_name=".$R['bd_name']."&sel=".$sel."'> ".$R['title']."</a>$memo</td>";
                }
            ?>
            </td>
            <td><?php echo $R['totalcnt'];?></td>
            <td><?php echo $R['startdate'];?></td>
            <td><?php echo $R['enddate'];?></td>
            <td><?php echo $status;?></td>
        </tr>
        <?php $i++;endforeach;?>
    </tbody>
</table>
<div><br></div>
<div class='searchbox'>
    <form name="searchf" class="form-inline" action="<?php echo $url.'?'.$link_url;?>">
        <input type="hidden" name="mode" value="<?php echo $mode?>" />
        <input type="hidden" name="sel" value="<?php echo $sel?>" />
        <input type="hidden" name="p" value="1" />
        <select name="where" class="form-control input-sm">
            <option value="unify">통합</option>
            <option value="title">제목</option>
            <option value="content">설명</option>
        </select>
        <div class="input-group input-group-sm">
            <input type="text" name="keyword" value="" class="form-control input-search" placeholder="검색어">
            <span class="input-group-btn">
                <button type="button" class="btn btn-default" onclick="this.form.where.value='title';this.form.keyword.value='',this.form.submit();" title="리셋"><i class="glyphicon glyphicon-repeat"></i></button>
                <button type="submit" class="btn btn-info" title="검색"><i class="glyphicon glyphicon-search"></i></button>
            </span>
        </div>
    </form>
</div>
<div class="pull-right info">
    <a href="<?php echo $g['bbs_reset']?>" class="btn btn-default btn-sm pull-right">처음목록</a>
</div>
<?php $b->PageLinkView($url,$NUM,$rowsPage,$curPage,$link_url);?>
</td>
</tr>
</table>
</div>
</body>
</html>
<?php mysqli_close($db);?>
 

 

<?php
class bbsClass extends MySQLDbClass {
 
    function PageLinkView($link_url$totalcnt$rowsPage$curPage$m) {
        echo '<div id="paging">';
        echo '<ul class="pagination">';
        $Info = $this -> PageList($totalcnt$rowsPage$curPage'');
        if ($Info['current_block'> 2) {
            echo "<li><a href='" . $link_url . "?p=1&$m'>◀</a></li> ";
        }
        if ($Info['current_block'> 1) {
            echo "<li><a href='" . $link_url . "?p=" . $Info['prev'] . "&$m'>◁</a></li> ";
        }
        foreach ($Info['current'as $w) {
            if ($curPage == $w) {
                echo "<li class='act'><a href='" . $link_url . "?p=" . $w . "&$m'><span style='color:red;'>" . $w . "</span></a></li> ";
            } else {
                echo "<li><a href='" . $link_url . "?p=" . $w . "&$m'>" . $w . "</a></li> ";
            }
        }
        if ($Info['current_block'< ($Info['total_block'])) {
            echo "<li><a href='" . $link_url . "?p=" . $Info['next'] . "&$m'>▷</a></li> ";
        }
        if ($Info['current_block'< ($Info['total_block'- 1)) {
            echo "<li><a href='" . $link_url . "?p=" . $Info['totalPage'] . "&$m'>▶</a></li> ";
        }
        echo '</ul>';
        echo '</div>';
    }
 
    // $curPage : 현재 페이지, $totalcnt : 총 게시물수
    // $block_limit : 한 화면에 뿌려질 게시글 개수
    function PageList($totalcnt,$rowsPage,$curPage,$block_limit) {
        $block_limit = $block_limit ? $block_limit : 10;  // 한 화면에 보여줄 개수 기본 10으로 설정
 
        // 총 페이지수 구하기
        $totalPage = ceil($totalcnt/$rowsPage);
        if($totalPage == 0) {
            ++$totalPage;
        }
        $total_block = ceil($totalPage / $block_limit); //전체 블록 갯수
 
        $curPage = $curPage ? $curPage : 1// 현재 페이지
 
        // 현재 블럭 : 화면에 표시될 페이지 리스트
        $current_block=ceil($curPage/$block_limit);
        // 현재 블럭에서 시작페이지
        $fstPage = (((ceil($curPage/$block_limit)-1)*$block_limit)+1);
        // 현재 블럭에서 마지막 페이지
        $endPage = $fstPage + $block_limit -1;
        if($totalPage < $endPage) {
            $endPage = $totalPage;
        }
 
        // 시작 바로 전 페이지
        $prev_page = $fstPage - 1;
        // 마지막 다음 페이지
        $next_page = $endPage + 1;
 
        foreach(range($fstPage$endPageas $val) {
            $row[] = $val;
        }
        // 배열로 결과를 돌려준다.
        return array(
            'total_block' => $total_block,
            'current_block' => $current_block,
            'totalPage' => $totalPage,
            'fstPage' => $fstPage,
            'endPage' => $endPage,
            'prev' => $prev_page,
            'next' => $next_page,
            'current' => $row
        );
    }
 
    //총페이지수
    function getTotalPage($num,$rec){
        return @intval(($num-1)/$rec)+1;
    }
 
}//end class boardClass

 

 
<?php
extract($_GET);
extract($_POST);
class MySQLDbClass {
    protected $db;
    private $host = 'localhost';
    private $database = 'survey';
    private $userid = 'root';
    private $password = 'autoset';
 
    public function __construct() {
        $this->db = $this->connectDB();
    }
 
    function __destruct(){
        mysqli_close($this->connectDB());
        //mysqli_close($this->db);
    }
 
    private function connectDB() {
        $dbconn = mysqli_connect($this->host, $this->userid, $this->password, $this->database);
        mysqli_set_charset($dbconn"utf8"); // DB설정이 잘못되어 euc-kr 로 되어 있으면 문제가 됨
        if (mysqli_connect_errno()) {
           printf("Connect failed: %s\n", mysqli_connect_error());
           exit();
        } else {
          return $dbconn;
        }
    }
 
    //DB-UID데이터
    function getUidData($table,$uid){
        return $this->getDbData($table,'uid='.(int)$uid,'*');
    }
 
    // DB Query Cutom 함수
    function getDbData($table,$where,$column) {
        $result = mysqli_query($this->db,'select '.$column.' from '.$table.($where?' where '.$this->getSqlFilter($where):''));
        $row = mysqli_fetch_array($result);
        return $row;
    }
 
    // DB Query result 함수
    function getDbresult($table,$where,$column) {
        $result = mysqli_query($this->db,'select '.$column.' from '.$table.($where?' where '.$this->getSqlFilter($where):''));
        return $result;
    }
 
    //DB데이터 ARRAY -> 테이블에 출력할 데이터 배열
    function getDbArray($table,$where,$flddata,$orderby,$rowsPage,$curPage){
        $sql = 'select '.$flddata.' from '.$table.($where?' where '.$this->getSqlFilter($where):'').($orderby?' order by '.$orderby:'').($rowsPage?' limit '.(($curPage-1)*$rowsPage).', '.$rowsPage:'');
        if($result = mysqli_query($this->db,$sql)){
            return $result;
        }
    }
 
    //DB데이터 레코드 총 개수
    function getDbRows($table,$where){
        $sql = 'select count(*) from '.$table.($where?' where '.$this->getSqlFilter($where):'');
        if($result = mysqli_query($this->db,$sql)){
            $rows = mysqli_fetch_row($result);
            return $rows[0] ? $rows[0] : 0;
        }
    }
 
    //DB삽입
    function getDbInsert($table,$key,$val){
        mysqli_query($this->db,"insert into ".$table." (".$key.")values(".$val.")");
    }
 
    //DB업데이트
    function getDbUpdate($table,$set,$where){
        mysqli_query('set names utf8');
        mysqli_query('set sql_mode=\'\'');
        mysqli_query($this->db,"update ".$table." set ".$set.($where?' where '.$this->getSqlFilter($where):''));
    }
 
    //DB삭제
    function getDbDelete($table,$where)    {
        mysqli_query($this->db,"delete from ".$table.($where?' where '.$this->getSqlFilter($where):''));
    }
 
    //SQL필터링
    function getSqlFilter($sql){
        return $sql;
    }
 
}//end dbClass
 
?>

 

블로그 이미지

Link2Me

,