[PHP] 게시판 만들기 with MVC - 11 SubReply

2023. 12. 28. 14:31· PHP/Modern PHP
목차
  1. 대댓글
  2. View
  3. Script
  4. Model

 

이전글 : [PHP] 게시판 만들기 with MVC - 1부 Migration

이전글 : [PHP] 게시판 만들기 with MVC - 2부 Routing

이전글 : [PHP] 게시판 만들기 with MVC - 3부 View(List & Create)

이전글 : [PHP] 게시판 만들기 with MVC - 4부 Controller

이전글 : [PHP] 게시판 만들기 with MVC - 5부 Pagination

이전글 : [PHP] 게시판 만들기 with MVC - 6부 Read

이전글 : [PHP] 게시판 만들기 with MVC - 7부 Update & Delete

이전글 : [PHP] 게시판 만들기 with MVC - 8부 Lock

이전글 : [PHP] 게시판 만들기 with MVC - 9부 Reply(List & Create)

이전글 : [PHP] 게시판 만들기 with MVC - 10부 Reply(Update & Delete)

 

대댓글

이제 대댓글 기능을 만들어봅시다

지난 포스팅에서 Controller와 Route 작업은 모두 마쳤습니다.

View와 Model 작업만 하면 끝납니다.

 

View

getSubReplies로 댓글마다의 대댓글 목록을 가져와서 뿌릴 겁니다.

bbs/view/read.php

...
                        <!-- 댓글 섹션 -->
                        <div class="mt-4 card">
                            <div class="card-body">
                                <input type="hidden" class="reply-idx" value="<?= $replyInfo['idx'] ?>"/>
                                <div class="media-body mb-3">
                                    <h5 class="mt-0"><?= $replyInfo['name'] ?></h5>
                                    <p class="mb-0">작성일: <?= $replyInfo['created_at'] ?></p>
                                    <?= nl2br($replyInfo['content']) ?>
                                </div>
                                <button class="btn btn-primary btn-reply-edit" data-bs-toggle="modal"
                                        data-bs-target="#editModal">
                                    수정
                                </button>
                                <button class="btn btn-primary btn-reply-delete" data-bs-toggle="modal"
                                        data-bs-target="#deleteModal">
                                    삭제
                                </button>
                                <button class="btn btn-primary btnSubReply">
                                    대댓글
                                </button>
                            </div>
                        </div>
                        
                        // 추가
                        <?php
                        $subReplies = $reply->getSubReplies($replyInfo['idx']);
                        if ($subReplies) {
                            foreach ($subReplies as $subReplyInfo) {
                                ?>
                                <div class="mt-4 card ml-4">
                                    <div class="card-body">
                                        <input type="hidden" class="reply-idx" value="<?= $subReplyInfo['idx'] ?>"/>
                                        <div class="media-body mb-3">
                                            <h5 class="mt-0"><?= $subReplyInfo['name'] ?></h5>
                                            <p class="mb-0">작성일: <?= $subReplyInfo['created_at'] ?></p>
                                            <?= nl2br($subReplyInfo['content']) ?>
                                        </div>
                                        <button class="btn btn-primary btn-reply-edit" data-bs-toggle="modal"
                                                data-bs-target="#editModal">
                                            수정
                                        </button>
                                        <button class="btn btn-primary btn-reply-delete" data-bs-toggle="modal"
                                                data-bs-target="#deleteModal">
                                            삭제
                                        </button>
                                    </div>
                                </div>
                                <?php
                            }
                        }
                    }
                    include_once "part/editModal.php";
                    include_once "part/deleteModal.php";
                }
            }
        } else {
            echo "<script>alert('존재하지 않는 게시물입니다.');history.back();</script>";
        }
        ?>
    </div>
    <script src="/bbs/assets/script/read.js"></script>
</body>
</html>

 

Script

그러기 위해선 대댓글을 만들 form이 필요합니다.

Js로 대댓글 버튼을 누르면 바로 그 아래의 대댓글을 만들 수 있는 form을 동적으로 추가해 봅시다.

HTMl은 복사하는 게 정신에 이롭습니다.

 

script의 form을 보면 bbs/reply/create로 POST 요청을 하는 걸 알 수 있습니다

저번 포스트에서 분기를 나눈 게 대댓글도 같이 사용하기 위함입니다.

bbs/assets/script/read.js

$(document).ready(function () {
   ...

    // 대댓글 작성 폼 생성 기능
    $(".btnSubReply").click(function (){
        let replyIdx = $(this).parent().find(".reply-idx").val();
        let postIdx = $("#postIdx").val();
        let subReplyFormExist = $("#subReplyForm").length > 0;
        if (subReplyFormExist) {
            $("#subReplyForm").remove();
        }

        $(this).parent().parent().after(
            "<div class=\"mt-4 card ml-4\" id=\"subReplyForm\">\n" +
            "            <div class=\"card-body\">\n" +
            "                <form action=\"/bbs/reply/create\" method=\"post\">\n" +
            "                    <h5>대댓글</h5>\n" +
            "                    <input name=\"post_idx\" type=\"hidden\" class=\"reply-idx\" value=\""+postIdx+"\"/>\n" +
            "                    <div class=\"media-body mb-3\">\n" +
            "                        <input name=\"parent_idx\" type=\"hidden\" name=\"post_idx\" value=\""+replyIdx+"\">\n" +
            "                        <div class=\"form-row\">\n" +
            "                            <div class=\"form-group col-md-6\">\n" +
            "                                <label for=\"name\">Name</label>\n" +
            "                                <input type=\"text\" class=\"form-control\" name=\"name\" placeholder=\"Name을 입력해주세요.\">\n" +
            "                            </div>\n" +
            "                            <div class=\"form-group col-md-6\">\n" +
            "                                <label for=\"password\">Password</label>\n" +
            "                                <input type=\"password\" class=\"form-control\" name=\"pw\"\n" +
            "                                       placeholder=\"Password를 입력해주세요.\">\n" +
            "                            </div>\n" +
            "                        </div>\n" +
            "                        <label for=\"content\">내용:</label>\n" +
            "                        <textarea name=\"content\" class=\"form-control\" id=\"content\" rows=\"3\"></textarea>\n" +
            "                    </div>\n" +
            "                    <button class=\"btn btn-primary\" type=\"submit\">댓글 작성</button>\n" +
            "                </form>\n" +
            "            </div>\n" +
            "        </div>")
    })
});

Model

마지막으로 subReplyCreate와 getSubReplies를 만들어줍시다.

bbs/Model/Reply.php

<?php

namespace Model;

use PDOException;

class Reply extends BaseModel
{	
	...

    /**
     * 대댓글 만들기
     * @param $postIdx
     * @param $parentIdx
     * @param $name
     * @param $pw
     * @param $content
     * @return bool
     */
    public function subReplyCreate($postIdx, $parentIdx, $name, $pw, $content): bool
    {
        try {
            $hashed_pw = password_hash($pw, PASSWORD_DEFAULT);
            $query = "INSERT INTO replies (post_idx, parent_idx, name, pw, content) VALUES (:post_idx, :parent_idx, :name, :pw, :content)";
            return $this->conn->prepare($query)->execute([
                'post_idx' => $postIdx,
                'parent_idx' => $parentIdx,
                'name' => $name,
                'pw' => $hashed_pw,
                'content' => $content
            ]);
        } catch (PDOException  $e) {
            error_log($e->getMessage());
            return false;
        }
    }


    /**
     * 대댓글 목록 가져오기
     * @param $parentIdx
     * @return array
     */
    public function getSubReplies($parentIdx): array
    {
        try {
            $query = "SELECT * FROM replies WHERE parent_idx = :parent_idx ORDER BY idx DESC";
            $stmt = $this->conn->prepare($query);
            $stmt->execute([
                'parent_idx' => $parentIdx,
            ]);
            return $stmt->fetchAll();
        } catch (PDOException $e) {
            error_log($e->getMessage());
            return [];
        }
    }
}

 

결과는 아래와 같습니다.

반응형

'PHP > Modern PHP' 카테고리의 다른 글

[PHP] 게시판 만들기 with MVC - 12 Delete Dummy  (0) 2023.12.28
[PHP] 게시판 만들기 with MVC - 10부 Reply(Update & Delete)  (2) 2023.12.28
[PHP] 게시판 만들기 with MVC - 9부 Reply(List & Create)  (1) 2023.12.28
[PHP] 게시판 만들기 with MVC - 8부 Lock  (0) 2023.12.28
[PHP] 게시판 만들기 with MVC - 7부 Update & Delete  (0) 2023.12.27
  1. 대댓글
  2. View
  3. Script
  4. Model
'PHP/Modern PHP' 카테고리의 다른 글
  • [PHP] 게시판 만들기 with MVC - 12 Delete Dummy
  • [PHP] 게시판 만들기 with MVC - 10부 Reply(Update & Delete)
  • [PHP] 게시판 만들기 with MVC - 9부 Reply(List & Create)
  • [PHP] 게시판 만들기 with MVC - 8부 Lock
DSeung
DSeung
DSeung
Dev log
DSeung
  • 분류 전체보기 (192)
    • PHP (62)
      • Laravel (31)
      • Error (5)
      • Setting (11)
      • Modern PHP (15)
    • Go Lang (51)
      • Study (30)
      • Algorithm (17)
      • Setting (1)
      • Error (3)
    • Java (11)
      • Spring (3)
      • JSP (0)
      • Error (2)
      • Setting (2)
      • 단축키 (2)
    • JavaScript (6)
      • Modern JavaScript (4)
      • Node (1)
    • Android Kotlin (5)
      • Study (4)
      • Error (1)
    • 컴퓨팅 기술 (12)
      • 데이터베이스시스템 (4)
      • Docker (2)
      • 크롤링 & 스크래핑 (1)
      • API (1)
      • 클라우드 (1)
      • 네트워크 (1)
    • MySQL (7)
    • AWS (1)
    • Git (5)
      • GItLab (1)
      • GitHub (4)
    • 도메인 (2)
      • 안과 (2)
    • 자격증 (7)
      • SQLD (1)
      • 정보처리기사 (6)
    • Mac os (1)
    • 나머지 (13)
      • tistory (1)
      • 기타 (9)
      • 일기 (3)
    • 독서 (9)

인기 글

최근 글

블로그 메뉴

  • 홈
  • 태그
전체
오늘
어제
hELLO · Designed By 정상우.v4.2.0
DSeung
[PHP] 게시판 만들기 with MVC - 11 SubReply
상단으로

티스토리툴바

개인정보

  • 티스토리 홈
  • 포럼
  • 로그인

단축키

내 블로그

내 블로그 - 관리자 홈 전환
Q
Q
새 글 쓰기
W
W

블로그 게시글

글 수정 (권한 있는 경우)
E
E
댓글 영역으로 이동
C
C

모든 영역

이 페이지의 URL 복사
S
S
맨 위로 이동
T
T
티스토리 홈 이동
H
H
단축키 안내
Shift + /
⇧ + /

* 단축키는 한글/영문 대소문자로 이용 가능하며, 티스토리 기본 도메인에서만 동작합니다.