ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [MongoDB] 2. 몽고DB를 사용한 첫 웹 애플리케이션 제작
    CSE/MongoDB 2015. 6. 13. 11:38
    이번 포스팅을 통하여 블로그를 만들도록 하겠습니다.
    아주 간단한 포스트 작성, 대시보드, 수정, 삭제, 댓글 까지 작성하도록 하겠습니다.

    순서는 

     1. 블로그 포스트 작성기 구현
     2. 데이터베이스에서 아티클을 인출하기
     3. 블로그 대시보드 구현하기
     4. 블로그 편집기 구현하기
     5. 블로그 포스트 삭제하기
     6. 블로그 포스트에 댓글 올리기

     구성되어있습니다.

    위 작업을 하기 전에, cmd창 2개를 열어 mongod와 mongo 명령어를 쳐서 구동시켜야 겠죠??




    1. 블로그 포스트 작성기 구현
    구동을 시키고 난 뒤, 설치된 Bitnami의 apache2/htdocs 폴더 내에 blogpost.php 파일을 작성하여 아래 코드를 입력합니다.

    blogpost.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
    <?php
    $action = (!empty($_POST['btn_submit']) && ($_POST['btn_submit'] === 'Save')) ? 'save_article' : 'show_form';
     
    switch ($action) {
    case 'save_article':
    try {
    $connection = new Mongo();
    $database = $connection->selectDB('myblogsite');
    $collection = $database->selectCollection('articles');
    $article = array(
    'title' => $_POST['title'],
    'content' => $_POST['content'],
    'saved_at' => new MongoDate()
    );
     
    $collection->insert($article);
    } catch(MongoConnectionException $e) {
    die("Failed to connect to database ".$e->getMessage());
    } catch(MongoException $e) {
    die("Failed to insert data ".$e->getMessage());
    }
    break;
    case 'show_form':
    default:
    }
    ?>
     
    <!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>
                    <?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"/>
                            </p>
                            <h3> Content </h3>
                            <textarea name="content" rows="20"></textarea>
                            <p>
                                <input type="submit" name="btn_submit" value="Save"/>
                            </p>
                        </form>
                    <?php else:?>
                        <p>
                            Article saved. _id:<?php echo $article['_id'];?>
                            <a href="blogpost.php">
                            Write another one? </a>
                        </p>
                    <?php endif;?>
                </div<!-- End of div innercontentarea -->
            </div<!-- End of div contentarea -->
        </body>
    </html>
    cs




    아 그리고 실행하기 전에 blogpost.php와 같은 경로에 첨부파일 style.css를 다운받아서 넣어줍니다.



    그리고 실행을 해보세요!


     




    위와 같이 작성 웹페이지에 나오면, Title과 Content를 작성해서 Save 해보세요!!

    여기서 MongoDB의 강점을 하나 볼수 있습니다! myblogsite DB가 없는데 어떻게 그안의 articles Collection을 선택하죠??
    아래와 같은 코드에 의해 DB에 없는것을 확인 후, MongoDB가 동적으로 DB와 Collection을 생성해줍니다!! 
    CREATE 문 없이 만들다니... ㅎㄷㄷ 이네요... 


    도전과제!!

     

     blogpost.php 스크립트에서 HTML을 수정해 tags라는 레이블이 붙은 텍스트 필드를 만들고, 사용자는 아티클을 위한 태그 여러개를 이 필드에 입력 할 수 있다. 태그는 ,(쉼표)로 구분된다. PHP 코드를 수정해 삽입 중인 아티클 다큐먼트의 tags라는 배열 필드에 사용자가 제출한 태그를 저장하게 만들자!








      먼저, html을 작성하여 필드를 생성해 줍시다! 
     그 다음, php 코드에 태그를 쉼표 ​로 구분한다 했으니, 쉼표로 잘라서, 다큐먼트에 넣을수 있게 만들어야겠죠??

    여러분이 해보시길 바라겠습니다. 궁금하시면 질문 주시면 되구요!!





    2. 데이터베이스에서 아티클을 인출하기
    이번에는 blogs.php 파일을 생성하여 아래 코드를 입력합니다.

    blogs.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
    <?php
    try {
    $connection = new Mongo();
    $database = $connection->selectDB('myblogsite');
    $collection = $database->selectCollection('articles');
    } catch(MongoConnectionException $e) {
    die("Failed to connect to database ".$e->getMessage());
    }
     
    $cursor = $collection->find();
    ?>
     
    <!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>
                    <?php while ($cursor->hasNext()):
    $article = $cursor->getNext();
    ?>
                    <h2><?php echo $article['title'];?></h2>
                    <p>
                        <?php echo substr($article['content'], 0200).'...';?>
                    </p>
                    <a href="blog.php?id=<?php echo $article['_id']; ?>"> Read more </a>
                    <?php endwhile;?>
                </div>
            </div>
        </body>
    </html>
    cs

     






    다음으로 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
    <?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>
            </div>
        </body>
    </html>
    cs





     
    직접 열어볼까요?? blogs.php먼저 열어보도록 합시다! 아래와 같은 웹페이지가 출력되네요!


     




    여기서 Read more눌러보도록 하겠습니다. 아래와 같이 출력되네요!
    (저는 blog.php파일에 댓글까지 구현된 상태라 abc.php로 임시로 만들어서 출력했습니다.)








    다음으로 대시보드 구현하기로 넘어가겠습니다. 





    3. 블로그 대시보드 구현하기
    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
    <?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>
                                </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 echo $_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


     


    작성이 되면 웹페이지에서 확인해야겠죠?? 구현된 결과는 아래와 같습니다. 
    원래 이번 대시보드 구현에서 중점적으로 다룬점은 게시판 페이징하는 걸 보여드려야 되는데, 
    게시물이 많지가 않아서 지금은 보이지 않습니다... 무튼 구현은 된거죠! 한번씩 해보시길 바랍니다.






    자 요로코롬 DashBoard가 나오네요~ 

    여기까지 대시보드 구현이 완료되었습니다. 



    도전과제!!

     blogs.php를 다시 써서 다음과 같이 변경하자!

     - 홈페이지는 가장 최근에 저장된 아티클을 상단에 보여줘야 함

     - 모든 아티클을 보여주는 대신, 가장 최근에 저장된 아티클 10개만 상단에 보여줌

     - 홈페이지에서 쪽수 나누기 기능을 활성화해 사용자가 과거 아티클도 탐색가능하게 만듬





     html에서는 페이지 쪽수 나누기를 위해 하단에 표시를 하기위해 추가해줘야겠죠
     PHP에서는 할게 많군요... 최신 아티클만 sort해서 보임과 동시에 10개만 뿌려주고, 페이징 처리까지... 한번 해봐야 실력이 늘겠죠??
     dashboard를 참고하시면 쉽습니다~


    여러분이 해보시길 바라겠습니다. 궁금하시면 질문 주시면 되구요!!??
     

     

    한 포스팅에 너무 많은 내용이 있는 관계로 2-1로 쪼개서 작성하도록 하겠습니다!


    댓글

Designed by Tistory.