Write Page : PHP

DATE : 2023/11/22

앞서 게시판 : PHP에서 게시물 정보를 저장할 board table을 만들어주었다.

index page는 board table에 들어있는 정보를 꺼내다가 어떤 게시물이 있는 지 보여주는 페이지라면

반대로 정보를 넣어주는 페이지도 필요하다!!

이번 POST에서는 board table에 정보를 넣어주기 위한 페이지,

즉 글쓰기 페이지와 관련해 필요한 코드를 살펴볼 것이다.

[ write_post.php ]

<?php
    require_once("./jwt.php");

    $usr = getToken($_COOKIE['JWT'])['usr'];
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Write</title>
    <link rel="stylesheet" href="./css/write_post.css">
</head>
<body>
    <form action="./upload_board.php" method="post">
        <input type="text" name="author" value="<?=$usr;?>" style="display: none;">
        <div class="post_info">
            <label for="title">TITLE : </label>
            <input type="text" name="title" id="title" placeholder="Title">
        </div>
        <div class="post_info">
            <label for="content">CONTENT : </label>
            <textarea name="content" id="content" cols="60" rows="12" maxlength="4096"></textarea>
        </div>
        <button id="post_btn">POST</button>
    </form>
</body>
</html>

index page에서 테이블 밑에 제공되는 Write 버튼을 누르면 write_post.php로 이동하게 된다.

이 페이지의 용도를 설명하자면,

로그인을 완료한 사용자에게만 제공되는 기능으로 게시물을 작성할 수 있는 페이지이다.

작성할 내용은 아주 간단하게 제목과 내용으로만 이루어져 있고

작성을 마친 후, POST 버튼을 클릭하면 사용자가 작성한 정보가 board table로 들어가게 된다.

POST 버튼을 눌렀을 시, 실행되는 코드는 다음과 같다.

<?php
    require_once("./db_connect.php");
    $title = $_POST['title'];
    $content = $_POST['content'];
    $date = date("Y-m-d H:i:s");
    $author = $_POST['author'];
    $hit = 0;

    $sql = "INSERT INTO board values (default,'$title','$content','$date','$author','$hit')";
    $res = mysqli_query($conn, $sql);

    if(!$res) {
        echo '<script>alert("Post Upload Error");
            window.location.replace("./index.php");
        </script>';
    } else {
        echo '<script>alert("Your Article is Successfully Posted!");
            window.location.replace("./index.php");
        </script>';
    }
?>

table에 넣어줄 데이터를 각 변수에 할당하고 INSERT문을 실행해서 table에 정보를 넣어준다.

간단하게 게시물을 작성하고

POST 버튼 클릭! 클릭! 해주면

INSERT문이 문제 없이 실행되면 위와 같이 성공적으로 글이 업로드 되었다는 문구를 볼 수 있다.

사진에 보이는 ALERT 창에 확인을 눌러주면 바로 index page로 이동하게 되는 데

이는 board table에 내용이 추가된 후, 페이지를 다시 불러오는 것이기 때문에

방금 작성한 게시물의 정보가 게시판에 나오는 걸 확인할 수 있다!!

검색, 정렬, 페이징 등 게시판 기능과 관련해 남은 내용은 너무 많지만..

꾸준히 계속해서 업데이트 할 예정으로, 일단 이번 주차에 정리하는 건 여기까지! 😎

Last updated