PHP

게시판 기능 구현

IC 2023. 4. 25.

board.php

더보기
<?php
    include "../connect/connect.php";
    include "../connect/session.php";
?>
<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>게시판</title>

    <?php include "../include/head.php" ?>
</head>
<body class="gray">
    <?php include "../include/skip.php" ?>
    <!-- //skip -->

    <?php include "../include/header.php" ?>
    <!-- //header -->

    <main id="main" class="container">
        <div class="intro__inner center bmStyle">
            <picture class="intro__images small">
                <source srcset="../assets/img/join01.png, ../assets/img/join01@2x.png, ../assets/img/join01@3x.png">
                <img src="../assets/img/join01.png" alt="회원가입 이미지">
            </picture>
            <h2>게시판</h2>
            <p class="intro__text">
                웹디자이너, 웹 퍼블리셔, 프론트앤드 개발자를 위한 게시판입니다.<br>
                관련된 문의사항은 여기서 확인하세요!
            </p>
        </div>
        <!-- intro inner -->
        <div class="board__inner">
            <div class="board__search">
                <div class="left">
                    * 총 <em>111</em>건의 게시물이 등록되어 있습니다.
                </div>
                <div class="right">
                    <form action="#" name="#" method="post">
                        <fieldset>
                            <legend class="blind">게시판 검색 영역</legend>
                            <input type="search" placeholder="검색어를 입력하세요!">
                            <select name="#" id="#">
                                <option value="title">제목</option>
                                <option value="content">내용</option>
                                <option value="name">등록자</option>
                            </select>
                            <button type="submit" class="btnStyle3 white">검색</button>
                            <a href="boardWrite.php" class="btnStyle3">글쓰기</a>
                        </fieldset>
                    </form>
                </div>
            </div>
            <div class="board__table">
                <table>
                    <colgroup>
                        <col style="width: 5%">
                        <col>
                        <col style="width: 10%">
                        <col style="width: 15%">
                        <col style="width: 7%">
                    </colgroup>
                    <thead>
                        <tr>
                            <th>번호</th>
                            <th>제목</th>
                            <th>등록자</th>
                            <th>등록일</th>
                            <th>조회수</th>
                        </tr>
                    </thead>
                    <tbody>
                        <!-- <tr>
                            <td>1</td>
                            <td><a href="boardView.html">게시판 제목</a></td>
                            <td>황인찬</td>
                            <td>2023-04-24</td>
                            <td>34</td>
                        </tr> -->
<?php
    $sql = "SELECT b.boardID, b.boardTitle, m.youName, b.regTime, b.boardView FROM board b  JOIN members m ON(b.memberID = m.memberID) ORDER BY boardID DESC LIMIT 10";
    $result = $connect -> query($sql);
    if($result){
        $count = $result -> num_rows;
        if($count > 0){
            for($i=0; $i<$count; $i++){
                $info = $result -> fetch_array(MYSQLI_ASSOC);

                echo "<tr>";
                echo "<td>".$info['boardID']."</td>";
                echo "<td><a href='boardView.php?boardID={$info['boardID']}'>".$info['boardTitle']."</td>";
                echo "<td>".$info['youName']."</td>";
                echo "<td>".date('Y-m-d', $info['regTime'])."</td>";
                echo "<td>".$info['boardView']."</td>";
                echo "</tr>";
            }
        } else {
            echo "<tr><td colspan='4'>게시글이 없습니다. </td></tr>";
        }
    }
?>
                    </tbody>
                </table>
            </div>
            <div class="board__pages">
                <ul>
                    <li><a href="#">처음으로</a></li>
                    <li><a href="#">이전</a></li>
                    <li class="active"><a href="#">1</a></li>
                    <li><a href="#">2</a></li>
                    <li><a href="#">3</a></li>
                    <li><a href="#">4</a></li>
                    <li><a href="#">5</a></li>
                    <li><a href="#">6</a></li>
                    <li><a href="#">7</a></li>
                    <li><a href="#">다음</a></li>
                    <li><a href="#">마지막으로</a></li>
                </ul>
            </div>
        </div>
    </main>
    <!-- //main -->

    <?php include "../include/footer.php" ?>
    <!-- //footer -->
</body>
</html>

이 코드는 게시판 페이지를 구성하는 코드입니다. PHP를 이용하여 데이터베이스에서 게시글을 불러와서 게시판 목록을 출력하고 있습니다. 페이지 상단에는 검색 폼과 글쓰기 버튼이 있으며, 하단에는 페이지 네이션을 구성하고 있습니다.

이 코드에서는 DB 접속 정보와 세션 관련 코드, 페이지 상단/하단의 공통 영역을 구성하는 include 코드는 생략되어 있습니다. 따라서 해당 코드가 정상적으로 동작하려면 이 코드 외에도 다른 파일들이 함께 사용되어야 합니다.

boardModifySave.php

더보기
<?php
    include "../connect/connect.php";
    include "../connect/session.php";

    $boardID = $_GET['boardID'];
    $boardID = $connect->real_escape_string($boardID);

    // 게시글 정보 가져오기
    $sql = "SELECT * FROM board WHERE boardID = '{$boardID}'";
    $result = $connect->query($sql);
    $boardInfo = $result->fetch_array(MYSQLI_ASSOC);

    // 현재 로그인한 사용자와 게시글 작성자의 memberID 비교
    if($memberID !== $boardInfo['memberID']) {
        echo "<script>alert('수정 권한이 없습니다.'); location.href='board.php';</script>";
        exit;
    }

    // memberID가 일치하는 경우, 수정 페이지로 이동
    header('Location: boardModify.php?boardID='.$boardID);
?>
<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>게시판</title>
    <?php include "../include/head.php" ?>
    <!-- //head -->
</head>
<body class="gray">
    <?php include "../include/skip.php" ?>
    <!-- //skip -->
    <?php include "../include/header.php" ?>
    <!-- //header -->
    <main id="main" class="container">
        <div class="intro__inner bmStyle center">
            <picture class="intro__images small">
                <source srcset="../assets/img/intro01.png, ../assets/img/intro01@2x.png 2x, ../assets/img/intro01@3x.png 3x" />
                <img src="../assets/img/intro01.png" alt="소개이미지">
            </picture>
            <h2>게시글 수정하기</h2>
            <p class="intro__text">
                과거의 실수보다는 미래의 가능성에 집중하여 끊임없이 성장하고 발전하는 모습을 보여드리겠습니다.
                마지막으로 사용자의 니즈를 고려한 창의적이고 혁신적인 아이디어를 실현시켜, 가치 있는 기술을 제공하겠습니다.
            </p>
        </div>
        <div class="board__inner">
            <div class="board__write">
                <form action="boardModifySave.php" name="boardWriteSave" method="post">
                    <fieldset>
                        <legend class="blind">게시글 작성하기</legend>
<?php
    $boardID = $_GET['boardID'];

    $sql = "SELECT boardID, boardTitle, boardContents FROM board WHERE boardID = {$boardID}";
    $result = $connect -> query($sql);

    if($result){
        $info = $result -> fetch_array(MYSQLI_ASSOC);
        echo "<div style='display:none'><label for='boardID'>번호</label><input type='text' id='boardID' name='boardID' class='inputStyle' value='".$info['boardID']."'></div>";
        echo "<div><label for='boardTitle'>제목</label><input type='text' id='boardTitle' name='boardTitle' class='inputStyle' value='".$info['boardTitle']."'></div>";
        echo "<div><label for='boardContents'>내용</label><textarea name='boardContents' id='boardContents' rows='20'  class='inputStyle'>".$info['boardContents']."</textarea></div>";
    }
?>
                        <!-- <div>
                            <label for="boardTitle">제목</label>
                            <input type="text" id="boardTitle" name="boardTitle" class="inputStyle">
                        </div>
                        <div>
                            <label for="boardContents">내용</label>
                            <textarea name="boardContents" id="boardContents" rows="20" class="inputStyle"></textarea>
                        </div> -->
                        <button type="submit" class="btnStyle3">저장하기</button>
                    </fieldset>
                </form>
            </div>
        </div>
    </main>
    <!-- //main -->
    <?php include "../include/footer.php" ?>
    <!-- //footer -->
</body>
</html>

이 코드는 PHP로 작성된 게시글 수정 페이지의 코드입니다. 게시글 작성자와 로그인한 사용자의 memberID를 비교하여 같은 경우, 게시글 수정 페이지로 이동합니다. 만약 두 memberID가 다른 경우, "수정 권한이 없습니다."라는 알림창을 띄우고 게시판 페이지로 이동합니다.

이후 게시글 수정 페이지에서는 GET으로 전달받은 boardID를 사용하여 해당 게시글 정보를 가져와 폼에 입력합니다. 사용자는 제목과 내용을 수정한 후 "저장하기" 버튼을 누르면 boardModifySave.php로 이동하여 수정된 내용을 저장합니다.

이 코드에서는 include를 사용하여 다른 PHP 파일에 있는 코드를 불러와 사용합니다. 또한, MySQLi를 사용하여 데이터베이스에 접속하고 쿼리를 실행합니다.

boardModifySave.php

더보기
<?php
    include "../connect/connect.php";
    include "../connect/session.php";
    $boardID = $_POST['boardID'];
    $boardTitle = $_POST['boardTitle'];
    $boardContents = $_POST['boardContents'];
    $boardTitle = $connect -> real_escape_string($boardTitle);
    $boardContents = $connect -> real_escape_string($boardContents);
    $sql = "UPDATE board SET boardTitle = '{$boardTitle}', boardContents = '{$boardContents}' WHERE boardID = '{$boardID}'";
    $connect -> query($sql)
?>
<script>
    location.href = "board.php";
</script>

boardRemover.php

더보기
<?php
    include "../connect/connect.php";
    include "../connect/session.php";
    $boardID = $_GET['boardID'];
    $boardID = $connect -> real_escape_string($boardID);
    $sql = "DELETE FROM board WHERE boardID = {$boardID}";
    $connect -> query($sql);
?>
<script>
    location.href = "board.php";
</script>

이 코드는 PHP로 작성된 게시글 수정 페이지의 코드입니다. 게시글 작성자와 로그인한 사용자의 memberID를 비교하여 같은 경우, 게시글 수정 페이지로 이동합니다. 만약 두 memberID가 다른 경우, "수정 권한이 없습니다."라는 알림창을 띄우고 게시판 페이지로 이동합니다.

이후 게시글 수정 페이지에서는 GET으로 전달받은 boardID를 사용하여 해당 게시글 정보를 가져와 폼에 입력합니다. 사용자는 제목과 내용을 수정한 후 "저장하기" 버튼을 누르면 boardModifySave.php로 이동하여 수정된 내용을 저장합니다.

이 코드에서는 include를 사용하여 다른 PHP 파일에 있는 코드를 불러와 사용합니다. 또한, MySQLi를 사용하여 데이터베이스에 접속하고 쿼리를 실행합니다.

boardView.php

더보기
<?php
    include "../connect/connect.php";
    include "../connect/session.php";
?>
<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>게시판</title>

    <?php include "../include/head.php" ?>
</head>
<body class="gray">
    <?php include "../include/skip.php" ?>
    <!-- //skip -->

    <?php include "../include/header.php" ?>
    <!-- //header -->

    <main id="main" class="container">
<div class="intro__inner center">
    <picture class="intro__images small">
        <source srcset="../assets/img/join01.png, ../assets/img/join01@2x.png, ../assets/img/join01@3x.png">
        <img src="../assets/img/join01.png" alt="회원가입 이미지">
    </picture>
    <h2>게시물 보기</h2>
    <p class="intro__text">
    웹디자이너, 웹 퍼블리셔, 프론트앤드 개발자를 위한 게시판입니다.<br>
    관련된 문의사항은 여기서 확인하세요!
    </p>
</div>
<!-- intro inner -->

<div class="board__inner">
    <div class="board__view">
    <table>
        <colgroup>
        <col style="width: 20%">
        <col style="width: 80%">
        </colgroup>
        <tbody>
        <?php
        if (isset($_GET['boardID'])) {
            $boardID = $_GET['boardID'];
            // echo $boardID;
            $sql = "SELECT b.boardContents, b.boardTitle, m.youName, b.regTime, b.boardView FROM board b JOIN members m ON(m.memberID = b.memberID) WHERE b.boardID = {$boardID}";
            $result = $connect->query($sql);
            if ($result) {
            $info = $result->fetch_array(MYSQLI_ASSOC);
            echo "<tr><th>제목</th><td>" . $info['boardTitle'] . "</td></tr>";
            echo "<tr><th>등록자</th><td>" . $info['youName'] . "</td></tr>";
            echo "<tr><th>등록일</th><td>" . date('Y-m-d', $info['regTime']) . "</td></tr>";
            echo "<tr><th>조회수</th><td>" . $info['boardView'] . "WQ</td></tr>";
            echo "<tr><th>내용</th><td>" . $info['boardContents'] . "</td></tr>";
            } else {
            echo "<tr><td colspan='4'>게시글이 없습니다.</td></tr>";
            }
        } else {
            echo "<tr><td colspan='4'>게시글이 없습니다.</td></tr>";
        }
        ?>
        </tbody>
    </table>
    </div>
    <div class="board__btn mb100">
    <?php if (isset($_GET['boardID'])) { ?>
        <a href="boardModify.php?boardID=<?= $_GET['boardID'] ?>" class="btnStyle3">수정하기</a>
        <a href="boardRemover.php?boardID=<?= $_GET['boardID']?>" class="btnStyle3" onclick="return confirm('정말 삭제할거니?')">삭제하기</a>
    <?php } ?>
    <a href="board.php" class="btnStyle3">목록보기</a>
    </div>
</div>
</main>
    <!-- //main -->

    <?php include "../include/footer.php" ?>
    <!-- //footer -->
</body>
</html>

이 코드는 게시글 보기 페이지를 나타냅니다.

먼저, connect.php와 session.php 파일을 불러와서 데이터베이스에 연결하고 로그인한 사용자의 정보를 가져옵니다.

그리고 HTML 문서를 작성하고, 게시글의 제목, 등록자, 등록일, 조회수, 내용을 출력합니다. 게시글 번호는 GET 방식으로 전달되며, 이를 이용하여 해당 게시글의 정보를 데이터베이스에서 가져옵니다. 게시글이 존재하지 않을 경우 "게시글이 없습니다."라는 메시지를 출력합니다.

게시글 보기 페이지에서는 수정하기, 삭제하기, 목록보기 버튼을 제공합니다. 수정하기 버튼을 클릭하면 게시글 수정 페이지로 이동하고, 삭제하기 버튼을 클릭하면 게시글 삭제를 위한 페이지로 이동합니다.

마지막으로, header.php, skip.php, footer.php 파일을 불러와서 페이지의 헤더, 스킵 내비게이션, 푸터를 출력합니다.

boardWrite.php

더보기
<?php
    include "../connect/connect.php";
    include "../connect/session.php";
?>
<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>게시판</title>
    <?php include "../include/head.php" ?>
    <!-- //head -->
</head>
<body class="gray">
    <?php include "../include/skip.php" ?>
    <!-- //skip -->
    <?php include "../include/header.php" ?>
    <!-- //header -->
    <main id="main" class="container">
        <div class="intro__inner bmStyle center">
            <picture class="intro__images small">
                <source srcset="../assets/img/intro01.png, ../assets/img/intro01@2x.png 2x, ../assets/img/intro01@3x.png 3x" />
                <img src="../assets/img/intro01.png" alt="소개이미지">
            </picture>
            <h2>게시글 작성하기</h2>
            <p class="intro__text">
                과거의 실수보다는 미래의 가능성에 집중하여 끊임없이 성장하고 발전하는 모습을 보여드리겠습니다.
                마지막으로 사용자의 니즈를 고려한 창의적이고 혁신적인 아이디어를 실현시켜, 가치 있는 기술을 제공하겠습니다.
            </p>
        </div>
        <div class="board__inner">
            <div class="board__write">
                <form action="boardWriteSave.php" name="boardWriteSave" method="post">
                    <fieldset>
                        <legend class="blind">게시글 작성하기</legend>
                        <div>
                            <label for="boardTitle">제목</label>
                            <input type="text" id="boardTitle" name="boardTitle" class="inputStyle">
                        </div>
                        <div>
                            <label for="boardContents">내용</label>
                            <textarea name="boardContents" id="boardContents" rows="20" class="inputStyle"></textarea>
                        </div>
                        <button type="submit" class="btnStyle3">저장하기</button>
                    </fieldset>
                </form>
            </div>
        </div>
    </main>
    <!-- //main -->
    <?php include "../include/footer.php" ?>
    <!-- //footer -->
</body>
</html>

이 코드는 PHP와 HTML을 이용하여 작성된 파일입니다. 게시판의 글 작성 페이지를 나타냅니다. 이 페이지에서는 사용자가 글의 제목과 내용을 입력한 후 저장할 수 있습니다. 이 코드에서는 여러 파일로 분리된 코드를 가져와서 사용하고 있습니다. 예를 들어, "../connect/connect.php" 파일에서는 데이터베이스에 연결하는 코드를 가져오고, "../include/header.php" 파일에서는 웹 사이트의 헤더를 가져오는 코드를 가져오고 있습니다. 이 파일은 모바일 기기에서도 볼 수 있도록 반응형으로 디자인되어 있습니다.

boardWriteSave.php

더보기
<?php
    include "../connect/connect.php";
    include "../connect/session.php";

    $boardTitle = $_POST['boardTitle'];
    $boardContents = $_POST['boardContents'];
    $boardView = 1;
    $regTime = time();
    $memberID = $_SESSION['memberID'];

    $boardTitle = $connect -> real_escape_string($boardTitle);
    $boardContents = $connect -> real_escape_string($boardContents);

    $sql = "INSERT INTO board(memberID, boardTitle, boardContents, boardView, regTime) VALUES('$memberID', '$boardTitle', '$boardContents', '$boardView', '$regTime')";
    $connect -> query($sql);
?>

<script>
    location.href = "board.php";
</script>

이 코드는 게시글을 작성하고 저장하는 과정을 처리하는 PHP 코드입니다.

먼저, connect.php와 session.php 파일을 include하여 데이터베이스 연결과 로그인 상태를 확인합니다.

그 다음, $boardTitle, $boardContents, $boardView, $regTime, $memberID 변수를 선언합니다. 이 중 $boardTitle과 $boardContents는 게시글의 제목과 내용을, $boardView는 조회수를, $regTime은 현재 시간을, $memberID는 현재 로그인된 회원의 ID를 저장합니다.

그 후 $connect -> real_escape_string() 함수를 사용하여 $boardTitle과 $boardContents에 들어올 수 있는 SQL Injection 공격을 방지합니다.

마지막으로, $sql 변수에 게시글 정보를 INSERT하는 SQL 쿼리를 저장하고, $connect -> query() 함수를 사용하여 쿼리를 실행합니다. 이렇게 하면 게시글이 데이터베이스에 저장됩니다.

마지막으로, location.href = "board.php"; 코드를 사용하여 게시글을 작성한 후에는 게시글 목록 페이지로 이동하도록 합니다.

댓글