게시판 : PHP

DATE : 2023/11/22

PHP code로 테이블을 만들기 전에 게시물 정보를 저장해줄 공간이 필요하다!!

사용할 DB에 board 라는 이름으로 새 table을 만들어주었다.

board table에는 게시물을 구분할 고유 id와 (게시물을 구별할 식별 정보)

게시물의 제목, 내용, 작성일, 작성자, 조회수 정보가 들어가게 될 것이다.

이제 게시판 : HTML에서 손수 작성했던 테이블 내용 대신

DB에 저장된 내용을 가져와 게시판을 만들어줄 PHP code를 작성해보자!

[index.php] : 게시판 구현

...
    <div class="container">
        <div class="page_title">
            BOARD
        </div>
        <div class="table">
            <div class="funcs">
                <select name="Order" id="order">
                    <option value="date" autofocus>Date</option>
                    <option value="author">Author</option>
                    <option value="title">Title</option>
                </select>
                <input type="text" placeholder="Search" class="search">        
            </div>
            <table>
                <?php
                    $sql = "SELECT * from board";
                    $res = mysqli_query($conn, $sql);

                    if(!$res) {
                        echo "error";
                    } else if(mysqli_num_rows($res) == 0) {
                        echo "<tr><th>There is No Post</th></tr>";
                    } else {
                        echo "<tr><th></th><th>Title</th><th>Author</th><th>Date</th><th>Hit</th></tr>";
                        $cnt = mysqli_num_rows($res);
                        
                        $i = 0;
                        while($cnt > $i) {
                            $rows = mysqli_fetch_array($res);
                ?>
                            <tr>
                            <th><?=$i;?></th>
                            <th><?=$rows['title'];?></th>
                            <th><?=$rows['author'];?></th>
                            <th><?=$rows['date']?></th>
                            <th><?=$rows['hit']?></th>
                            </tr>
                <?php 
                            $i++;
                }} ?>
            </table>
            <div class="footer">
                <button id="write_btn">Write</button>
            </div>
        </div>
    </div>
    
    <script src="./btn.js"></script>
    <script src="https://kit.fontawesome.com/5b18c6ebda.js" crossorigin="anonymous"></script>
</body>
</html>

중복되는 내용은 건너뛰고 바-로 table tag를 확인해보자.

원래는 tr, th, td tag로 직접 테이블 내용을 작성했던 방식과 달리

깔끔하게 PHP code가 등장하였다. 그 내용을 주로 보자면

<?php
    $sql = "SELECT * from board";
    $res = mysqli_query($conn, $sql);

    if(!$res) { //에러
        echo "error";
    } else if(mysqli_num_rows($res) == 0) { //Post 없음 
        echo "<tr><th>There is No Post</th></tr>";
    } else {
        echo "<tr><th></th><th>Title</th><th>Author</th><th>Date</th><th>Hit</th></tr>";
        $cnt = mysqli_num_rows($res);
                        
        $i = 0;
        while($cnt > $i) {
            $rows = mysqli_fetch_array($res);
?>
    <tr>
        <th><?=$i;?></th>
        <th><?=$rows['title'];?></th>
        <th><?=$rows['author'];?></th>
        <th><?=$rows['date']?></th>
        <th><?=$rows['hit']?></th>
    </tr>                            
<?php 
    $i++;
}} ?>

게시물 정보를 저장하는 Table, board에서 모든 데이터를 꺼내오는 SQL을 실행한다.

query 결과가 한 줄도 없는 경우, 테이블에는 출력할 내용이 없기 때문에

"There is No Post" 문구를 출력하고

query 결과가 존재하는 경우에는 우선, column name으로 구성된 row를 table에 넣어준다.

$cnt = mysqli_num_rows($res);

$i = 0;
while($cnt > $i) {
    $rows = mysqli_fetch_array($res);
    ....
    $i++;
}

DB에서 모든 게시물을 가져왔을 때, 그 개수를 변수cnt로 정의하고

게시물의 개수 만큼 while문을 반복 실행하면서

<tr>
    <th><?=$i;?></th>
    <th><?=$rows['title'];?></th>
    <th><?=$rows['author'];?></th>
    <th><?=$rows['date']?></th>
    <th><?=$rows['hit']?></th>
</tr>

게시물의 제목, 저자, 작성일, 조회수 정보를 테이블에 한 줄로 넣어준다.

이때 while문 내에서 mysqli_fetch_array 함수를 실행하면

첫 번째 row부터 순서대로 데이터를 가져오기 때문에 따로 row의 순서를 지정할 필요가 없다!

예를 들어, $res에 총 3개의 게시물 정보가 들어 있다고 하면

$i = 0) first row in board table
$i++; 

$i = 1) second row in board table
$i++;

$i = 2) third row in board table
$i++;

자동으로 첫 번째 row 데이터를 가져오고 $i 값이 하나 증가한 다음,

또 다시 while문이 실행되면 이때는 두 번째 row의 데이터를 가져오게 된다.

while문의 조건이 참인 동안 계속 다음 row의 데이터를 가져오면서

테이블 row를 만들다가,

저장된 게시물의 정보를 모두 출력하게 되면 while문을 벗어나게 되는 것이다.


이제 PHP code로 구현한 내용이 제대로 동작하는 지 확인해보자!!

우선 확인해볼 부분은, board table에 어떤 정보도 들어있지 않은 경우이다.

코드에서 확인 했듯이 board table에서 모든 row를 가져왔을 때, row 개수가 0이면

"There is No Post" 문구가 나올 것이다.

페이지를 확인해보면 column name, data가 아닌 설정한 문구가 나오는 걸 확인할 수 있다.

그렇다면 이번에 board table에 임의로 데이터를 넣어,

페이지에서 해당 데이터로 테이블을 구성하는 지 확인해보자.

Write 버튼을 눌러 write_post page에서 글을 작성한 다음, DB를 확인해보면

성공적으로 정보가 저장된 건 확인!!

index page의 경우에는,

방금 입력한 게시물 정보가 간단한 리스트 형태로 나타나는 걸 볼 수 있다!!

Last updated