댓글용 테이블을 하나 만든다.
CREATE TABLE `memo` ( `memoid` int(11) NOT NULL AUTO_INCREMENT, `bid` int(11) DEFAULT NULL, `pid` int(11) DEFAULT NULL, `userid` varchar(100) DEFAULT NULL, `memo` varchar(300) DEFAULT NULL, `status` tinyint(4) DEFAULT 1, `regdate` datetime DEFAULT current_timestamp(), PRIMARY KEY (`memoid`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4;
무슨 테이블이던 마찬가지겠지만 처음부터 완벽하게 테이블을 설계하는 경우는 드물다. 하다보면 칼럼을 추가하거나 칼럼의 속성을 변경하거나 크기를 변경하거나 한다. 또 정답도 없다. 그러니 부담없이 만들어보자.
댓글을 입력하기 위하여 view.php를 수정해보자.
/view.php
<?php
include $_SERVER [ "DOCUMENT_ROOT" ] . "/inc/header.php" ;
$bid = $_GET [ "bid" ];
$result = $mysqli -> query ( "select * from board where bid=" . $bid ) or die ( "query error => " . $mysqli -> error );
$rs = $result -> fetch_object ();
? >
< h3 class = "pb-4 mb-4 fst-italic border-bottom" style = " text-align:center; " >
- 게시판 보기 -
</ h3 >
< article class = "blog-post" >
< h2 class = "blog-post-title" > <?php echo $rs -> subject ; ? > </ h2 >
< p class = "blog-post-meta" > <?php echo $rs -> regdate ; ? > by < a href = "#" > <?php echo $rs -> userid ; ? > </ a ></ p >
< hr >
< p >
<?php echo $rs -> content ; ? >
</ p >
< hr >
</ article >
< nav class = "blog-pagination" aria-label = "Pagination" >
< a class = "btn btn-outline-secondary" href = "/index.php" > 목록 </ a >
< a class = "btn btn-outline-secondary" href = "/write.php?parent_id= <?php echo $rs -> bid ; ? > " > 답글 </ a >
< a class = "btn btn-outline-secondary" href = "/write.php?bid= <?php echo $rs -> bid ; ? > " > 수정 </ a >
< a class = "btn btn-outline-secondary" href = "/delete.php?bid= <?php echo $rs -> bid ; ? > " > 삭제 </ a >
</ nav >
< div style = " margin-top:20px; " >
< form class = "row g-3" >
< div class = "col-md-10" >
< textarea class = "form-control" placeholder = "댓글을 입력해주세요." id = "floatingTextarea2" style = " height: 60px " ></ textarea >
</ div >
< div class = "col-md-2" >
< button type = "button" class = "btn btn-secondary" > 댓글등록 </ button >
</ div >
</ form >
</ div >
<?php
include $_SERVER [ "DOCUMENT_ROOT" ] . "/inc/footer.php" ;
? >
보기 화면이 아래와 같이 바뀌었다. 이제 댓글을 등록해주면 댓글 입력 창 아래쪽에 등록한 댓글이 나타나도록 작업해보자. 이번에도 ajax를 이용해보겠다. form을 이용할 수도 있지만 그건 옛날 방식이니 사용하지 않겠다.
저기 textarea에 글을 쓰고 댓글등록버튼을 클릭하면 본 게시물의 고유번호(bid)와 텍스트 내용을 입력해준다. ajax를 이용해 텍스트를 넘겨주고 디비에 저장한 후 위 화면 아래에 댓글 내용을 붙이기 위해 파일을 하나 만든다.
그전에 일단 view.php를 다시 수정한다. ajax부분을 추가해준다.
/view.php
<?php
include $_SERVER [ "DOCUMENT_ROOT" ] . "/inc/header.php" ;
$bid = $_GET [ "bid" ];
$result = $mysqli -> query ( "select * from board where bid=" . $bid ) or die ( "query error => " . $mysqli -> error );
$rs = $result -> fetch_object ();
? >
< h3 class = "pb-4 mb-4 fst-italic border-bottom" style = " text-align:center; " >
- 게시판 보기 -
</ h3 >
< article class = "blog-post" >
< h2 class = "blog-post-title" > <?php echo $rs -> subject ; ? > </ h2 >
< p class = "blog-post-meta" > <?php echo $rs -> regdate ; ? > by < a href = "#" > <?php echo $rs -> userid ; ? > </ a ></ p >
< hr >
< p >
<?php echo $rs -> content ; ? >
</ p >
< hr >
</ article >
< nav class = "blog-pagination" aria-label = "Pagination" >
< a class = "btn btn-outline-secondary" href = "/index.php" > 목록 </ a >
< a class = "btn btn-outline-secondary" href = "/write.php?parent_id= <?php echo $rs -> bid ; ? > " > 답글 </ a >
< a class = "btn btn-outline-secondary" href = "/write.php?bid= <?php echo $rs -> bid ; ? > " > 수정 </ a >
< a class = "btn btn-outline-secondary" href = "/delete.php?bid= <?php echo $rs -> bid ; ? > " > 삭제 </ a >
</ nav >
< div style = " margin-top:20px; " >
< form class = "row g-3" >
< div class = "col-md-10" >
< textarea class = "form-control" placeholder = "댓글을 입력해주세요." id = "memo" style = " height: 60px " ></ textarea >
</ div >
< div class = "col-md-2" >
< button type = "button" class = "btn btn-secondary" id = "memo_button" > 댓글등록 </ button >
</ div >
</ form >
</ div >
< div id = "memo_place" >
<!-- <div class="card mb-4" style="max-width: 100%;margin-top:20px;">
<div class="row g-0">
<div class="col-md-2 text-dark bg-light">
</div>
<div class="col-md-10">
<div class="card-body">
<h5 class="card-title">Card title</h5>
<p class="card-text">This is a wider card with supporting text below as a natural lead-in to additional content. This content is a little bit longer.</p>
<p class="card-text"><small class="text-muted">Last updated 3 mins ago</small></p>
</div>
</div>
</div>
</div> -->
</ div >
< script >
$ ( "#memo_button" ). click ( function () {
var data = {
memo : $ ( '#memo' ). val () ,
bid : <?php echo $bid ; ? >
};
$ . ajax ({
async : false ,
type : 'post' ,
url : 'memo_write.php' ,
data : data ,
dataType : 'html' ,
error : function () {} ,
success : function ( return_data ) {
if ( return_data == "member" ){
alert ( '로그인 하십시오.' );
return ;
} else {
$ ( "#memo_place" ). append ( return_data );
}
}
});
});
</ script >
<?php
include $_SERVER [ "DOCUMENT_ROOT" ] . "/inc/footer.php" ;
? >
ajax에서 호출할 파일을 만든다.
/memo_write.php
<?php session_start ();
include $_SERVER [ "DOCUMENT_ROOT" ] . "/inc/dbcon.php" ;
ini_set ( 'display_errors' , '0' );
if (! $_SESSION [ 'UID' ]){
echo "member" ;
exit ;
}
$memo = $_POST [ 'memo' ];
$bid = $_POST [ 'bid' ];
$memoid = $_POST [ 'memoid' ]?? 0 ;
$sql = " INSERT INTO memo
(bid, pid, userid, memo, status )
VALUES ( " . $bid . ", " . $memoid . ", '" . $_SESSION [ 'UID' ] . "', '" . $memo . "', 1)" ;
$result = $mysqli -> query ( $sql ) or die ( $mysqli -> error );
if ( $result ) $last_memoid = $mysqli -> insert_id ;
echo "<div class= \" card mb-4 \" style= \" max-width: 100%;margin-top:20px; \" >
<div class= \" row g-0 \" >
<div class= \" col-md-12 \" >
<div class= \" card-body \" >
<p class= \" card-text \" >" . $memo . "</p>
<p class= \" card-text \" ><small class= \" text-muted \" >" . $_SESSION [ 'UID' ] . " / now</small></p>
</div>
</div>
</div>
</div>" ;
? >
소스를 위에서 부터 보면 일단 로그인을 안하고 댓글을 쓰면 입력이 안되도록 막는 부분이 있고 그리고 넘겨준 데이터를 받아 디비에 입력해준 후 그 값을 바탕으로 뷰 화면에 보여줄 html을 만들어서 리턴해준다.
이번엔 뷰화면에서 댓글을 입력해보자
이렇게 붙어서 보이면 성공이다. 물론 이상태에서 새로고침하면 이 댓글은 사라지고 안보인다. 새로고침해도 보이도록 view.php를 수정해보자
/view.php
<?php
include $_SERVER [ "DOCUMENT_ROOT" ] . "/inc/header.php" ;
$bid = $_GET [ "bid" ];
$result = $mysqli -> query ( "select * from board where bid=" . $bid ) or die ( "query error => " . $mysqli -> error );
$rs = $result -> fetch_object ();
$query = "select * from memo where status=1 and bid=" . $rs -> bid . " order by memoid asc" ;
$memo_result = $mysqli -> query ( $query ) or die ( "query error => " . $mysqli -> error );
while ( $mrs = $memo_result -> fetch_object ()){
$memoArray []= $mrs ;
}
? >
< h3 class = "pb-4 mb-4 fst-italic border-bottom" style = " text-align:center; " >
- 게시판 보기 -
</ h3 >
< article class = "blog-post" >
< h2 class = "blog-post-title" > <?php echo $rs -> subject ; ? > </ h2 >
< p class = "blog-post-meta" > <?php echo $rs -> regdate ; ? > by < a href = "#" > <?php echo $rs -> userid ; ? > </ a ></ p >
< hr >
< p >
<?php echo $rs -> content ; ? >
</ p >
< hr >
</ article >
< nav class = "blog-pagination" aria-label = "Pagination" >
< a class = "btn btn-outline-secondary" href = "/index.php" > 목록 </ a >
< a class = "btn btn-outline-secondary" href = "/write.php?parent_id= <?php echo $rs -> bid ; ? > " > 답글 </ a >
< a class = "btn btn-outline-secondary" href = "/write.php?bid= <?php echo $rs -> bid ; ? > " > 수정 </ a >
< a class = "btn btn-outline-secondary" href = "/delete.php?bid= <?php echo $rs -> bid ; ? > " > 삭제 </ a >
</ nav >
< div style = " margin-top:20px; " >
< form class = "row g-3" >
< div class = "col-md-10" >
< textarea class = "form-control" placeholder = "댓글을 입력해주세요." id = "memo" style = " height: 60px " ></ textarea >
</ div >
< div class = "col-md-2" >
< button type = "button" class = "btn btn-secondary" id = "memo_button" > 댓글등록 </ button >
</ div >
</ form >
</ div >
< div id = "memo_place" >
<?php
foreach ( $memoArray as $ma ){
? >
< div class = "card mb-4" style = " max-width: 100%;margin-top:20px; " >
< div class = "row g-0" >
< div class = "col-md-12" >
< div class = "card-body" >
< p class = "card-text" > <?php echo $ma -> memo ; ? > </ p >
< p class = "card-text" >< small class = "text-muted" > <?php echo $ma -> userid ; ? > / <?php echo $ma -> regdate ; ? > </ small ></ p >
</ div >
</ div >
</ div >
</ div >
<?php } ? >
</ div >
< script >
$ ( "#memo_button" ). click ( function () {
var data = {
memo : $ ( '#memo' ). val () ,
bid : <?php echo $bid ; ? >
};
$ . ajax ({
async : false ,
type : 'post' ,
url : 'memo_write.php' ,
data : data ,
dataType : 'html' ,
error : function () {} ,
success : function ( return_data ) {
if ( return_data == "member" ){
alert ( '로그인 하십시오.' );
return ;
} else {
$ ( "#memo_place" ). append ( return_data );
}
}
});
});
</ script >
<?php
include $_SERVER [ "DOCUMENT_ROOT" ] . "/inc/footer.php" ;
? >
이런식으로 해주면 된다. 글이 길어져서 다음장에선 수정과 삭제를 해보겠다.