본문 바로가기

Web

[Web] php, mysql을 활용한 게시판 글 작성 구현 / 웹개발-7

 

드디어 게시판을 만들어볼 예정이다. 물론 디자인은 포기..

 

오늘 만든 것은 글 작성 기능이다. 게시판 기능은 로그인 한 사용자에 한해서 사용이 가능하다.

 

login_success.php


 

<?php
include "/opt/homebrew/var/www/db/db_init.php";

session_start();

if (!isset($_SESSION["username"])) {
    echo "<script>
    alert('로그인이 필요합니다.');
    location.href='/';
    </script>";
} else {
    echo "환영합니다 " . $_SESSION["username"] . "님";
}
?>

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf8">
        <title>로그인 성공</title>
        <link href="/css/style.css" rel="stylesheet"/>

    </head>

    <body>
        <br><a href="/login/logout.php">로그아웃</a>
        <a href="/login/mypage.php">마이페이지</a>
        <a href="/member/select.php">프로필 조회</a>
        <div class="container">
            <table class="list" cellspacing="0" cellpadding="0";>
                    <tr>
                        <th width="70">번호</th>
                        <th width="400">제목</th>
                        <th width="250">작성자</th>
                        <th width="300">작성일</th>
                    </tr>
<?php

$sql = "select * from board order by board_id desc limit 0, 10";
$result = $conn->query($sql);
$num = $result->num_rows;
while ($row = $result->fetch_assoc()) {?>
                    <tr>
                        <td><?php echo $num ?></td>
                        <td><?php echo $row["title"] ?></td>
                        <td><?php echo $row["writer"] ?></td>
                        <td><?php $now_time = time() - intval($row["date"]);
    if ($now_time < 60) {
        $now_time = strval($now_time) . "초 전";
    } else if ($now_time >= 60 && $now_time < 3600) {
        $now_time = intdiv($now_time, 60);
        $now_time = strval($now_time) . "분 전";
    } else if ($now_time >= 3600 && $now_time < 86400) {
        $now_time = intdiv($now_time, 3600);
        $now_time = strval($now_time) . "시간 전";
    } else if ($now_time >= 86400) {
        $now_time = intdiv($now_time, 86400);
        $now_time = strval($now_time) . "일 전";
    }
    echo $now_time;
    ?></td>
                    </tr>
<?php $num -= 1;}?>
            </table>
        </div>
            <div class="title_box">게시판</div>
            <div class="button_box">
                <form action="/board/write.php" method="get">
                    <input type="submit" value="글쓰기">
                </form>
                    <input class="delete" type="button" value="삭제">
            </div>
</body>
</html>

 

 

👆 현재까지 완성된 게시판이다. 현재 페이지에서는 DB에 저장된 글들을 가져와 화면에 뿌려줘야한다. 따라서 board 테이블에 있는 모든 행을 반환하는 쿼리문을 날려준다. 이때 게시판의 경우 오래된 글일 수록 밑에 쌓이게 된다. 따라서 미리 DB의 board_id에 auto_increment를 줬기 때문에 이 값을 기준으로 내림차순(작은 숫자가 먼저 오도록, 즉 오래된 글이 먼저옴) 정렬된 행들을 반환하도록 한다. 

 

DB 구조, 추가예정

 

mysql의 auto_increment 옵션은 행이 삭제되어도 번호에 대한 갱신 없이 계속 증가한다. 따라서 게시판의 번호로 쓰기 적절치 않기 때문에 따로 num 변수를 선언해 번호를 매겼다.

 

디자인은 넘어가고 바로 글쓰기 버튼이 눌러졌을 때의 로직을 처리하는 write.php를 설명하겠다.

 

 

write.php


 

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf8">
        <title>글쓰기</title>
    </head>
    <body>
        <h2>게시판</h4>

        <div id=write_area>
            <form action="/board/write_ok.php" method="post">
                <div id="write_title">
                    <textarea name="title" id="title" rows="1" cols="55" placeholder="제목" maxlength="100" required></textarea>
                </div>
                <div id=write_name>
                    <textarea name="name" id="name" rows="1" cols="55" placeholder="글쓴이" maxlength="100" required></textarea>
                </div>
                <div id=write_content>
                    <textarea name="content" id="content" placeholder="내용" required></textarea>
                </div>
                <button type="submit">글 작성</button>
            </form>
        </div>
    </body>
</html>

 

 

글 작성의 경우에는 디자인이 전혀 되지 않은 걸 볼 수 있다. 디자인에 목메지 말자! 사실 write.php 보다는 글 작성 버튼이 눌렸을 때의 로직을 처리하는 코드가 메인이기 때문에 다음 코드를 보도록 하겠다.

 

 

write_ok.php


<?php
include "/opt/homebrew/var/www/db/db_init.php";

$title = $_POST['title'];
$name = $_POST['name'];
$content = $_POST['content'];
$date = time();

$sql = "INSERT INTO board (writer, title, content, date) VALUES ('$name', '$title', '$content', '$date')";

$result = $conn->query($sql);
print_r($result);

if ($result) {
    echo "<script>alert('게시글이 등록되었습니다.'); location.href='/login/login_success.php'</script>";
} else {
    echo "<script>alert('게시글 등록에 실패하였습니다.')</script>";
}

 

위 코드는 글 작성 버튼이 눌렸을 때 데이터들을 DB에 저장하는 로직이다. 특별한 건 없고 DB에 저장된 글들을 화면에 뿌려줄때 작성 시간을 표현하기 위해 글 작성 시 시각을 time() 메소드를 통해 같이 넣어준다.

 

 

지금보니 작성된 글을 볼 수 있는 기능을 안 넣었다..