게시판 - 댓글 삭제

이태현·2025년 9월 18일

Web 개발

목록 보기
52/53
post-thumbnail

Frontend

board_view.js

  // 댓글 삭제
  const btn_comment_deletes = document.querySelectorAll(".btn_comment_delete")
  btn_comment_deletes.forEach((box) => {
    box.addEventListener('click', () => {
      if (!confirm('삭제 하시겠습니까?')) {
        return false
      }
      const f = new FormData()
      f.append('pidx', params['idx'])
      f.append('idx', box.dataset.commentIdx)
      f.append('mode', 'delete')

      const xhr = new XMLHttpRequest()
      xhr.open('post', 'pg/comment_process.php', true)
      xhr.send(f)
      xhr.onload = () => {
        if (xhr.status == 200) {
          const data = JSON.parse(xhr.responseText)
          if (data.result == 'success') {
            location.reload()
          }
        } else if (xhr.status == 404) {
          alert('통신 실패 : ' + xhr.status)
        }
      }
    })
  })

Backend

comment_process.php

else if ($mode == 'delete') {
  if ($pidx == '') {
    $arr = ['result' => 'empty_pidx'];
    die(json_encode($arr));
  }
  if ($idx == '') {
    $arr = ['result' => 'empty_idx'];
    die(json_encode($arr));
  }

  $comment->delete($pidx, $idx);
  $arr = ['result' => 'success'];
  die(json_encode($arr));
}

DB

Comment Class

  // 댓글 삭제
  public function delete($pidx, $idx)
  {
    // 댓글 갯수 감소
    $sql = "UPDATE board SET comment_cnt=comment_cnt-1 WHERE idx=:pidx";
    $stmt = $this->conn->prepare($sql);
    $params = [':pidx' => $pidx];
    $stmt->execute($params);

    // 댓글 삭제
    $sql = "DELETE FROM comment WHERE idx=:idx";
    $stmt = $this->conn->prepare($sql);
    $params = [':idx' => $idx];
    $stmt->execute($params);
  }

결과

Before


현재 댓글이 2개 있습니다.

After


결과 - DB

Before

After


게시글 삭제로 댓글 개수가 하나 감소하였습니다.

마무리

다음 시간에는 댓글 수정부분을 해보겠습니다.

감사합니다.

profile
이해하고 분석하고 지배한다

0개의 댓글