Almon Dev

게시판 만들기 #6 (게시글 삭제하기) 본문

모의해킹/웹 개발

게시판 만들기 #6 (게시글 삭제하기)

Almon 2024. 11. 12. 17:11

게시판 만들기

 

게시글 삭제하기

 

delete_post.js

function deletePost(e, postId, categoryId, categoryName) {
  e.preventDefault();

  if (confirm('게시글을 삭제하시겠습니까?')) {
    url = '/forum/db/delete_post.php';
    fetch(url, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json; charset=utf-8',
      },
      body: JSON.stringify({
        post_id: postId,
        category_id: categoryId,
      }),
    })
      // .then((res) => res.text())
      // .then(console.log);
      .then((res) => res.json())
      .then((res) => {
        if (res.token) {
          postList(categoryId, categoryName, 1);
        } else {
          window.location.href = '/logout.php';
        }
      });
  }
}

삭제 버튼을 누르면 confirm으로 확인을 한 뒤, 게시글 번호를 delete_post.php에 post요청을 보냅니다.

삭제에 성공하면 카테고리의 1페이지로 돌아갑니다.

 

delete_post.php

<?php
require_once("../../jwt_auth.php");
require_once("../../mysql.php");
// echo "test";

if($token = Jwt_auth::auth()) {
    $post = json_decode(file_get_contents("php://input"), true);
    $category_id = $post['category_id'] ?? null;
    $post_id = $post['post_id'] ?? null;
    
    if ($category_id != null && $post_id != null) {
        // echo "test";
        $user_id = $token->sub;
        $id = runSQL("select id from users where user_id='$user_id'")->fetch_array()['id'];
        $writer_id = runSQL("select writer_id from posts where post_id=$post_id")->fetch_array()['writer_id'];

        // echo $id . "  " . $writer_id;

        if($id == $writer_id) {
            // echo "test";
            $sql = "delete from posts where post_id=$post_id";
            runSql($sql);

            echo json_encode(["result" => true, "token" => true]);
            exit;
        }
    }
}
echo json_encode(["result" => false, "token" => false]);
	$user_id = $token->sub;
        $id = runSQL("select id from users where user_id='$user_id'")->fetch_array()['id'];
        $writer_id = runSQL("select writer_id from posts where post_id=$post_id")->fetch_array()['writer_id'];

        // echo $id . "  " . $writer_id;

        if($id == $writer_id) {

토큰의 sub에 있는 사용자의 아이디(문자)를 이용해서 db에 저장된 사용자의 아이디(숫자)를 가져옵니다.

전달받은 게시글 번호와 일치하는 작성자의 아이디를 가져와서 요청을 보낸 사용자와 게시글 작성자가 일치한지를 확인합니다.

 

            $sql = "delete from posts where post_id=$post_id";
            runSql($sql);

            echo json_encode(["result" => true, "token" => true]);

delete문으로 게시글을 삭제하고 결과를 응답합니다.


마무리