ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [MongoDB] 2-1. 몽고DB를 사용한 첫 웹 애플리케이션 제작
    CSE/MongoDB 2015. 6. 13. 11:39
    이어서 계속 가겠습니다. 




    4. 블로그 편집기 구현하기



     edit.php파일 생성하여 아래 소스 넣어주세요.

    edit.php 
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    <?php
    $action = (!empty($_POST['btn_submit']) && ($_POST['btn_submit'] === 'Save')) ? 'save_article' : 'show_form';
     
    $id = $_REQUEST['id'];
    try {
    $mongodb = new Mongo();
    $articleCollection = $mongodb->myblogsite->articles;
    } catch(MongoConnectionException $e) {
    die('Failed to connect to MongoDB '$e->getMessage());
    }
     
    switch ($action) {
    case 'save_article':
    $article = array();
    $article['title'] = $_POST['title'];
    $article['content'] = $_POST['content'];
    $article['saved_at'] = new MongoDate();
    $articleCollection->update(array('_id' => new MongoId($id)), $article);
    break;
     
    case 'show_form':
    default:
    $article = $articleCollection->findOne(array('_id' => new MongoId($id)));
    }
    ?>
     
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml" lang="en">
        <head>
            <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
            <link rel="stylesheet" href="style.css"/>
            <title> Blog Post Editor </title>
        </head>
        <body>
            <div id="contentarea">
                <div id="innercontentarea">
                    <h1> Blog Post Creator </h1>
                    <?php if ($action === 'show_form'):?>
                        <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
                            <h3> Title </h3>
                            <p><input type="text" name="title" id="title" value="<?php echo $article['title']; ?>" /></p>
                            <h3> Content </h3>
                            <textarea name="content" rows="20">
                                <?php echo $article['content'];?>
                            </textarea>
                            <input type="hidden" name="id" value="<?php echo $article['_id']; ?>" />
                            <p>
                                <input type="submit" name="btn_submit" value="Save" />
                            </p>
                        </form>
                    <?php else:?>
                        <p>
                            Article saved. _id: <?php echo $id;?>.
                            <a href="blog.php?id=<?php echo $id; ?>">
                                Read it.
                            </a>
                        </p>
                    <?php endif;?>
                </div<!--div innercontentarea End -->
            </div>
        </body>
    </html>
    cs






    그 다음, 이전에 작성한 dashboard.php의 요 부분을 !!! 수정하셔야 합니다. 일단 찾으세요!
    dashboard.php

     

    1
    2
    3
    4
                                <td class="url">
                                    <a href="blog.php?id=<?php echo $article['_id']; ?>"> View </a>
                                </td>
     
    cs




    이렇게 추가해 주세요!!
    dashboard.php

     

    1
    2
    3
    4
    5
                                <td class="url">
                                    <a href="blog.php?id=<?php echo $article['_id']; ?>"> View </a>
                                    | <a href="edit.php?id=<?php echo $article['_id']; ?>"> Edit </a>
                                </td>
     
    cs

     






    그 다음은 웹에서 확인해야겠죠?? dashboard.php에서 보면 아마 edit 버튼이 생겼을 껍니다!
    edit 버튼 눌러서 수정이 되는지 확인하세요!





    여기서 잠깐!! 짚고넘어갈 연산이 있습니다!
    바로 upsert 요놈은 '존재하면 update, 존재하지 않으면 insert'하는 신기방기한 연산입니다.
    혹여나, 개발중에 필요한 연산일것같으므로 짚고 넘어갔습니다!

    사용방법은 아래와 같습니다.
     $user->update(array('email') => 'alice@wonderland.com'), array('firstname' => 'Alice', 'lastname' => 'Liddell'), array('unsert' => True));

    요롷코롷 해주시면 됩니다!!



    도전과제!!

     

     blogpost.php는 작성용, edit.php는 갱신용이다. 두 모듈이 하는 작업을 하나로 합친 새 모듈을 만들자. 새 모듈의 동작은 다음과 같다.


     - 기본적으로, 페이지는 사용자가 블로그 포스트를 위한 제목과 내용을 입력하도록 HTML 폼을 보여준다.(이미 클리어)

     - 페이지가 GET 매개변수의 ID를 받으면, HTML 폼에서 아티클의 제목과 내용을 보여준다. 

     - 사용자가 폼에서 Save 버튼을 클릭할 때, 아티클은 DB에 저장된다.(힌틔 save() 나 upsert 기능 사용_

       · 새로운 아티클인 경우: 아티클 삽입

       · 그렇지 않으면: 아티클 갱신

     - 아티클이 갱신될 때, 전체 아티클 객체를 대체하는 대신 아티클의 제목과 내용만 갱신되어야 함. 또한 modified_at라는 새로운 필드에 아티클이 갱신된 마지막 시각을 기록한다. 



    그럼 다음으로 넘어가겠습니다.




    5. 블로그 포스트 삭제하기


    dashboard.php를 열어 수정을 해야합니다!! 그냥 새로 작성하죠;; 편하게ㅋ

    dashboard.php


    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
     
    <?php
    // Mongo DB 연결 부
    try {
    $mongodb = new Mongo();
    $articleCollection = $mongodb->myblogsite->articles;
    } catch(MongoConnectionException $e) {
    die("Failed to connect to database ".$e->getMessage());
    }
     
    $currentPage = (isset($_GET['page'])) ? (int$_GET['page'] : 1;
    $articlesPerPage = 5;
    $skip = ($currentPage - 1) * $articlesPerPage;
     
    $cursor = $articleCollection->find(array(), array('title','saved_at'));
    $totalArticles = $cursor->count();
    $totalPages = (int) ceil($totalArticles / $articlesPerPage);
     
    $cursor->sort(array('saved_at'=>-1))->skip($skip)->limit($articlesPerPage);
     
    ?>
     
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml" lang="en">
        <head>
            <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
            <link rel="stylesheet" href="style.css"/>
            <style type="text/css" media="screen">
    body {font-size: 13px; }
    div#contentarea {width: 650px;}
    </style>
            <title> DashBoard </title>
            <script type="text/javascript" charset="utf-8">
    function confirmDelete(articleId) {
    var deleteArticle = confirm('Are you sure you want to delete this article?');
    if (deleteArticle) {
    window.location.href = 'delete.php?id='+articleId;
    }
    return;
    }
    </script>
        </head>
        <body>
            <div id="contentarea">
                <div id="innercontentarea">
                    <h1> DashBoard </h1>
                    <table class="articles" cellspacing="0" cellpadding="0">
                        <thead>
                            <tr>
                                <th width="55%"> Title </th>
                                <th width="27%"> Created at </th>
                                <th width="*"> Action </th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php
    while($cursor->hasNext()):
    $article = $cursor->getNext();
    ?>
                            <tr>
                                <td>
                                    <?php echo substr($article['title'], 035). '...';?>
                                </td>
                                <td>
                                    <?php print date('g:i a, F j'$article['saved_at']->sec);?>
                                </td>
                                <td class="url">
                                    <a href="blog.php?id=<?php echo $article['_id']; ?>"> View </a>
                                    | <a href="edit.php?id=<?php echo $article['_id']; ?>"> Edit </a>
                                    | <a href="#" onclick="confirmDelete('<?php echo $article['_id']; ?>')"> Delete </a>
                                </td>
                            </tr>
                            <?php endwhile;?>
                        </tbody>
                    </table>
                </div<!--div innercontentarea End -->
                <div id="navigation">
                    <div class="prev">
                        <?php if($currentPage !== 1):?>
                        <a href="<?php echo $_SERVER['PHP_SELF'].'?page='.($currentPage -1); ?>"> Previous </a>
                        <?php endif;?>
                    </div><!--div prev End -->
                    
                    <div class="page-number">
                        <?php echo $currentPage;?>
                    </div<!--div page-number End-->
                    
                    <div class="next">
                        <?php if ($currentPage !== $totalPages):?>
                        <a href="<?php $_SERVER['PHP_SELF'].'?page='.($currentPage + 1); ?>"> Next </a>
                        <?php endif;?>
                    </div<!--div Next End-->
                    <br class="clear">
                </div><!--div navigation End-->
            </div>
        </body>
    </html>
    cs

     

     





    다음으로 delete.php를 만들어주세요.

    delete.php


    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    <?php
    $id = $_GET['id'];
    try {
    $mongodb = new Mongo();
    $articleCollection = $mongodb->myblogsite->articles;
    } catch(MongoConnectionException $e) {
    die('Failed to connect to MongoDB '$e->getMessage());
    }
     
    $articleCollection->remove(array('_id' => new MongoId($id)));
    ?>
     
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml" lang="en">
        <head>
            <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
            <link rel="stylesheet" href="style.css"/>
            <title> Blog Post Creator </title>
        </head>
        <body>
            <div id="contentarea">
                <div id="innercontentarea">
                    <h1> Blog Post Creator </h1>
                    <p> Article deleted. _id: <? echo $id;?>.
                    <a href="dashboard.php"> Go Back to dashboard? </a>
                </div<!--div innercontentarea End -->
            </div>
        </body>
    </html>
    cs






    확인 스크린 샷은 굳이 뽑지 않겠습니다ㅋ 삭제 되니까용...







    6. 블로그 포스트에 댓글올리기

    마지막으로 댓글입니다!!

    blog.php를 아래와 같이 다시 작성해주세요

    blog.php
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    <?php
    $id = $_GET['id'];
    try {
    $connection = new Mongo();
    $database = $connection->selectDB('myblogsite');
    $collection = $database->selectCollection('articles');
    } catch(MongoConnectionException $e) {
    die("Failed to connect to database ".$e->getMessage());
    }
    $article = $collection->findOne(array('_id' => new MongoId($id)));
    ?>
     
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml" lang="en">
        <head>
            <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
            <link rel="stylesheet" href="style.css"/>
            <title> My Blog Site </title>
        </head>
        <body>
            <div id="contentarea">
                <div id="innercontentarea">
                    <h1> My Blogs </h1>
                    <h2<?php echo $article['title'];?></h2>
                    <p<?php echo $article['content'];?></p>
                    <div id="comment_section">
                        <h3> Comments </h3>
                        <?php if (!empty($article['comments'])):?>
                            <h3> comment </h3>
                            <?php foreach($article['comments'as $comment):
    echo $comment['name']. ' says...';?>
                            <p<?php echo $comment['comment'];?></p>
                            <span>
                                <?php echo date('g:i a, F j'$comment['posted_at']->sec);?>
                            </span><br /><br /><br />
                        <?php endforeach; endif;?>
                        
                        <h3> Post your comment </h3>
                        <form action="comment.php" method="post">
                            <span class="input-label"> Name </span>
                            <input type="text" name="commenter_name" class="comment-input"/>
                            <br/><br/>
                            <span class="input-label"> E-mail </span>
                            <input type="text" name="commenter_email" class="comment-input"/>
                            <br/><br/>
                            <textarea name="comment" rows="5"></textarea>
                            <br/><br/>
                            <input type="hidden" name="article_id" value="<?php echo $article['_id']; ?>" />
                            <input type="submit" name="btn_submit" value="Save"/>
                        </form>
                    </div<!-- End of div comment_section -->
                </div>
            </div>
        </body>
    </html>
    cs

     




    다음으로 comment.php를 작성해주세요
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    <?php
    $id = $_POST['article_id'];
     
    try {
    $mongodb = new Mongo();
    $collection = $mongodb->myblogsite->articles;
    } catch(MongoConnectionException $e) {
    die("failed to connect to MongoDB ."$e->getMessage());
    }
     
    $comments = array
    'name' => $_POST['commenter_name'],
    'email' => $_POST['commenter_email'],
    'comment' => $_POST['comment'],
    'posted_at' => new MongoDate()
    );
     
    $collection->update(array('_id' => new MongoId($id)), array('$push' => array('comments' => $comments)));
    header('Location: blog.php?id='.$id);
    ?>
    cs

     





    확인을 해보겠습니다!
    먼저, blogs.php로 접근해서 목록을 확인하고 Read more를 통해 접근하겠습니다.







    아래와 같이 창이 뜨면, 임의로 작성하고 save 눌러보도록 하겠습니다.








    Save를 누르니 아래와 같이 댓글이 올라가 있네요!!!








    도전과제!!



     

     사용자 이름이 Bob인 사람이 올린 모든 댓글을 얻는 몽고DB 질의를 작성하자!



     






    이상으로 블로그 구현 포스팅을 마무리 하겠습니다!! 

     









     


    댓글

Designed by Tistory.