반응형

지난 시간까지 클래스를 가볍게 알아봤으니 이번엔 지금까지 했던 게시판을 클래스를 이용해 변경해 보도록 하겠다. 하는김에 현재 만들어진 게시판을 멀티게시판으로 변경해보자.

 

ALTER TABLE `board` 
ADD COLUMN `multi` VARCHAR(20) NULL AFTER `parent_id`;

update board set multi="free" where multi is null;

 

위 쿼리를 실행해서 board 테이블에 multi라고 하는 컬럼을 추가해 준 후 multi에 "free"라는 값을 업데이트 해 준다. 지금까지의 모든 게시물들은 free(자유게시판)에 속하게 된다. 

 

간단하게 컬럼을 추가해서 멀티게시판을 만들었다. 이제 multi에 다른 값을 넣어주면 그건 새로운 게시판이 된다.

 

클래스를 이용한다고 했으니 클래스를 만들어주겠다. lib.php를 수정한다.

 

/lib/lib.php

<?php include $_SERVER["DOCUMENT_ROOT"]."/inc/dbcon.php";

//글 작성자의 이름을 가져오기 위해 함수를 사용했다. 매개변수인 userid를 통해 이름을 알아낸 후 그 값을 리턴해 준다.
function member_name($userid){
    global $mysqli;//$mysqli 는 dbconn.php에서 만들어진 변수이기때문에 함수안에서 사용하려면 global로 선언해주어야한다.
    $query = "select username from members where userid='".$userid."'";
    $result = $mysqli->query($query) or die("query error => ".$mysqli->error);
    $rs = $result->fetch_object();
    return $rs->username;
}

class Boards {
    private $boardName;//게시판명
    private $boardCount;//게시물수
    private $boardLastDate;//마지막으로 게시물이 등록된 날짜

    public function boardname($multi){
        switch($multi) {
            case "free":$rs="자유게시판";
            break;
            case "humor":$rs="유머게시판";
            break;
            case "star":$rs="연예인게시판";
            break;
        }
        return $rs;
    }

    public function __construct($multi="free"){//생성자다. 생성자에 파라미터가 있다. 파라미터값이 없으면 "free"로 지정한다.
        global $mysqli;
        $query = "select regdate, cnt from board b1
        join (
                select b2.multi, count(*) as cnt from board b2 where status=1 group by b2.multi
        ) board2 on b1.multi=board2.multi
        where b1.multi='".$multi."'
        and status=1 order by bid desc limit 1;";
        $result = $mysqli->query($query) or die("query error => ".$mysqli->error);
        $rs = $result->fetch_object();
        $this->boardName=self::boardname($multi);
        $this->boardCount=$rs->cnt;
        $this->boardLastDate=$rs->regdate;
    }

    public function boardInfo(){
        $bi = array(
            "boardName"=>$this->boardName,
            "boardCount"=>$this->boardCount,
            "boardLastDate"=>$this->boardLastDate
        );
        return $bi;//게시판 정보를 배열로 만들어서 리턴한다.
    }

   
}

?>

Boards라는 이름의 클래스를 만들었다. 생성자는 게시판의 기본정보를 담고 있다. 이 생성자에 있는 기본 정보를 가져와서 게시판에 표시해보자.

 

/index.php

<?php
include $_SERVER["DOCUMENT_ROOT"]."/inc/header.php";

$search_keyword = $_GET['search_keyword'];

if($search_keyword){
    $search_where = " and (subject like '%".$search_keyword."%' or content like '%".$search_keyword."%')";
}

$pageNumber  = $_GET['pageNumber']??1;//현재 페이지, 없으면 1
if($pageNumber < 1) $pageNumber = 1;
$pageCount  = $_GET['pageCount']??10;//페이지당 몇개씩 보여줄지, 없으면 10
$startLimit = ($pageNumber-1)*$pageCount;//쿼리의 limit 시작 부분
$firstPageNumber  = $_GET['firstPageNumber'];


$sql = "select b.*, if((now() - regdate)<=86400,1,0) as newid
,(select count(*) from memo m where m.status=1 and m.bid=b.bid) as memocnt
,(select m.regdate from memo m where m.status=1 and m.bid=b.bid order by m.memoid desc limit 1) as memodate
,(select count(*) from file_table f where f.status=1 and f.bid=b.bid) as filecnt
,(select filename from file_table_summer fs where fs.status=1 and fs.bid=b.bid order by fs.fid asc limit 1) as thumb
from board b where 1=1";
$sql .= " and status=1";
$sql .= $search_where;
$order = " order by ifnull(parent_id, bid) desc, bid asc";
$limit = " limit $startLimit, $pageCount";
$query = $sql.$order.$limit;
//echo "query=>".$query."<br>";
$result = $mysqli->query($query) or die("query error => ".$mysqli->error);
while($rs = $result->fetch_object()){
    $rsc[]=$rs;
}

//전체게시물 수 구하기
$sqlcnt = "select count(*) as cnt from board where 1=1";
$sqlcnt .= " and status=1";
$sqlcnt .= $search_where;
$countresult = $mysqli->query($sqlcnt) or die("query error => ".$mysqli->error);
$rscnt = $countresult->fetch_object();
$totalCount = $rscnt->cnt;//전체 게시물 갯수를 구한다.
$totalPage = ceil($totalCount/$pageCount);//전체 페이지를 구한다.

if($firstPageNumber < 1) $firstPageNumber = 1;
$lastPageNumber = $firstPageNumber + $pageCount - 1;//페이징 나오는 부분에서 레인지를 정한다.
if($lastPageNumber > $totalPage) $lastPageNumber = $totalPage;

if($firstPageNumber > $totalPage) {
    echo "<script>alert('더 이상 페이지가 없습니다.');history.back();</script>";
    exit;
}
    $multi=$_GET['multi']??"free";//게시판 구분자
    $boards = new Boards($multi);//인스턴스를 생성한다
?>
        <div><?php //클래스 적용부분
            $bi=$boards->boardInfo();
            echo $bi["boardName"]." ( 총 게시물수 : ".$bi["boardCount"]." / 마지막등록일 : ".$bi["boardLastDate"].")";
        ?></div>
        <!-- 더보기 버튼을 클릭하면 다음 페이지를 넘겨주기 위해 현재 페이지에 1을 더한 값을 준비한다. 더보기를 클릭할때마다 1씩 더해준다. -->
        <input type="hidden" name="nextPageNumber" id="nextPageNumber" value="<?php echo $pageNumber+1;?>">
        <table class="table">
        <thead>
            <tr>
            <th scope="col">번호</th>
            <th scope="col">글쓴이</th>
            <th scope="col">썸네일</th>
            <th scope="col">제목</th>
            <th scope="col">등록일</th>
            </tr>
        </thead>
        <tbody id="board_list">
            <?php
                $idNumber = $totalCount - ($pageNumber-1)*$pageCount;
                foreach($rsc as $r){
                    //검색어만 하이라이트 해준다.
                    $subject = str_replace($search_keyword,"<span style='color:red;'>".$search_keyword."</
                        span>",$r->subject);
                   
            ?>

                <tr>
                    <th scope="row"><?php echo $idNumber--;?></th>
                    <td><?php echo member_name($r->userid);?></td>
                    <td><?php
                        if(!empty($r->thumb)){
                            echo "<img src='/data/".$r->thumb."' width='50'>";
                        }else{
                            echo "null";
                        }
                    ?></td>
                    <td>
                        <?php
                            if($r->parent_id){
                                echo "&nbsp;&nbsp;<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"16\" height=\"16\" fill=\"currentColor\" class=\"bi bi-arrow-return-right\" viewBox=\"0 0 16 16\">
                                <path fill-rule=\"evenodd\" d=\"M1.5 1.5A.5.5 0 0 0 1 2v4.8a2.5 2.5 0 0 0 2.5 2.5h9.793l-3.347 3.346a.5.5 0 0 0 .708.708l4.2-4.2a.5.5 0 0 0 0-.708l-4-4a.5.5 0 0 0-.708.708L13.293 8.3H3.5A1.5 1.5 0 0 1 2 6.8V2a.5.5 0 0 0-.5-.5z\"/>
                              </svg>";
                            }
                        ?>  
                    <a href="/view.php?bid=<?php echo $r->bid;?>"><?php echo $subject?></a>
                    <?php if($r->filecnt){?>
                        <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-card-image" viewBox="0 0 16 16">
                        <path d="M6.002 5.5a1.5 1.5 0 1 1-3 0 1.5 1.5 0 0 1 3 0z"/>
                        <path d="M1.5 2A1.5 1.5 0 0 0 0 3.5v9A1.5 1.5 0 0 0 1.5 14h13a1.5 1.5 0 0 0 1.5-1.5v-9A1.5 1.5 0 0 0 14.5 2h-13zm13 1a.5.5 0 0 1 .5.5v6l-3.775-1.947a.5.5 0 0 0-.577.093l-3.71 3.71-2.66-1.772a.5.5 0 0 0-.63.062L1.002 12v.54A.505.505 0 0 1 1 12.5v-9a.5.5 0 0 1 .5-.5h13z"/>
                        </svg>
                    <?php }?>
                    <?php if($r->memocnt){?>
                        <span <?php if((time()-strtotime($r->memodate))<=86400){ echo "style='color:red;'";}?>>
                            [<?php echo $r->memocnt;?>]
                        </span>
                    <?php }?>
                    <?php if($r->newid){?>
                        <span class="badge bg-danger">New</span>
                    <?php }?>
                </td>
                    <td><?php echo $r->regdate?></td>
                </tr>
            <?php }?>
        </tbody>
        </table>
        <div class="d-grid gap-2" style="margin:20px;">
            <button class="btn btn-secondary" type="button" id="more_button">더보기</button>
        </div>
        <form method="get" action="<?php echo $_SERVER["PHP_SELF"]?>">
        <div class="input-group mb-12" style="margin:auto;width:50%;">
                <input type="text" class="form-control" name="search_keyword" id="search_keyword" placeholder="제목과 내용에서 검색합니다." value="<?php echo $search_keyword;?>" aria-label="Recipient's username" aria-describedby="button-addon2">
                <button class="btn btn-outline-secondary" type="button" id="search">검색</button>
        </div>
        </form>
        <!-- <p>
            <nav aria-label="Page navigation example">
                <ul class="pagination justify-content-center">
                    <li class="page-item">
                        <a class="page-link" href="<?php echo $_SERVER['PHP_SELF']?>?pageNumber=<?php echo $firstPageNumber-$pageCount;?>&firstPageNumber=<?php echo $firstPageNumber-$pageCount;?>&search_keyword=<?php echo $search_keyword;?>&multi=<?php echo $multi;?>">Previous</a>
                    </li>
                    <?php
                        for($i=$firstPageNumber;$i<=$lastPageNumber;$i++){
                    ?>
                        <li class="page-item <?php if($pageNumber==$i){echo "active";}?>"><a class="page-link" href="<?php echo $_SERVER['PHP_SELF']?>?pageNumber=<?php echo $i;?>&firstPageNumber=<?php echo $firstPageNumber;?>&search_keyword=<?php echo $search_keyword;?>&multi=<?php echo $multi;?>"><?php echo $i;?></a></li>
                    <?php
                        }
                    ?>
                    <li class="page-item">
                        <a class="page-link" href="<?php echo $_SERVER['PHP_SELF']?>?pageNumber=<?php echo $firstPageNumber+$pageCount;?>&firstPageNumber=<?php echo $firstPageNumber+$pageCount;?>&search_keyword=<?php echo $search_keyword;?>&multi=<?php echo $multi;?>">Next</a>
                    </li>
                </ul>
            </nav>
        </p> -->

        <p style="text-align:right;">

            <?php
                if($_SESSION['UID']){
            ?>
                <a href="write.php"><button type="button" class="btn btn-primary">등록</button><a>
                <a href="/member/logout.php"><button type="button" class="btn btn-primary">로그아웃</button><a>
            <?php
                }else{
            ?>
                <a href="/member/login.php"><button type="button" class="btn btn-primary">로그인</button><a>
                <a href="/member/signup.php"><button type="button" class="btn btn-primary">회원가입</button><a>
            <?php
                }
            ?>
        </p>

<script>
    $("#more_button").click(function () {
       
        var data = {//more_list_page.php에 넘겨주는 파라미터 값이다.
            pageNumber : $('#nextPageNumber').val() ,
            pageCount : <?php echo $pageCount;?>,
            totalCount : <?php echo $totalCount;?>,
            search_keyword : <?php echo $search_keyword;?>
        };
            $.ajax({
                async : false ,
                type : 'post' ,//post방식으로 넘겨준다. ajax는 반드시 post로 해준다.
                url : 'more_list_page.php' ,
                data  : data ,//위에서 만든 파라미터들을 넘겨준다.
                dataType : 'html' ,//리턴받을 형식이다. html말고 text난 json도 있다. json을 가장 많이 쓴다.
                error : function() {} ,
                success : function(return_data) {
                    if(return_data==false){
                        alert('마지막 페이지입니다.');
                        return;
                    }else{
                        $("#board_list").append(return_data);//table 마지막에 붙여준다. 반대는 prepend가 있다.
                        $("#nextPageNumber").val(parseInt($('#nextPageNumber').val())+1);//다음페이지를 위해 1씩 증가해준다.
                    }
                }
        });
    });
</script>

<?php
include $_SERVER["DOCUMENT_ROOT"]."/inc/footer.php";

이런 식으로 게시판의 기본 정보를 클래스를 이용해서 가져와 화면에 표시해 주었다. 다음과 같이 나온다.

 

지금은 자유게시판을 호출했다. 주소에 별다른 값을 입력하지 않으면 디폴트값은 "free"이다 이번엔 multi에 다른 값을 줘서 화면을 열어보자.

 

http://localhost:8008/?multi=star

 

이런식으로 뒤에다가 파라미터를 붙여주면 해당 게시판으로 변경된다.(localhost:8008은 내 컴퓨터에 설정때문이다.)

 

 

multi값을 바꾸면 새로운 게시판으로 바뀐걸 알 수 있다. 하지만 아직 게시물 출력 부분은 수정을 안했기때문에 게시물 리스트는 자유게시판과 같다.

 

다음 시간엔 게시물의 리스트도 클래스를 이용해서 가져와보도록 하겠다. 

 

반응형

+ Recent posts