ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [CodeIgniter] 4. 게시판 프로젝트 - 수정, 삭제
    Web/CodeIgniter 2015. 8. 23. 15:13

    4.5 수정 기능 추가하기

     수정기능은 입력 기능을 수정하여 사용합니다. write 메서드를 복사하여 modify 메서드를 만들고 수정합니다.


     

     * bbs/application/controllers/board.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
    <?php
    if (!defined('BASEPATH'))
        exit('No direct script access allowed');
    /**
     *  게시판 메인 컨트롤러
     */
     
    class Board extends CI_Controller {
     
     
         ....
     
     
        /**
         * 게시물 수정
         */
        function modify() {
            echo '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />';
            
            if ( $_POST ) {
                $this -> load -> helper('alert');
                
                $uri_array = $this->segment_explode($this->uri->uri_string());
                
                if ( in_array('page'$uri_array)) {
                    $pages = urldecode($this->url_explode($uri_array'page'));
                } else {
                    $pages = 1;
                }
                
                if ( !$this->input->post('subject', TRUE) AND !$this->input->post('contents', TRUE)) {
                    alert('비정상적인 접근입니다.''bbs/board/lists/'.$this->uri->segment(3).'/page/'.$pages);
                    exit;
                }
                
                
                $modify_data = array(
                    'table' => $this->uri->segment(3),
                    'board_id' => $this->uri->segment(5),
                    'subject' => $this->input->post('subject', TRUE),
                    'contents' => $this->input->post('contents', TRUE)
                );
                
                $result = $this->board_m->modify_board($modify_data);
                
                if ( $result ) {
                    alert('수정되었습니다.''bbs/board/lists/'.$this->uri->segment(3).'/page/'.$pages);
                    exit;
                } else {
                    alert('다시 수정해 주세요.''bbs/board/view/'.$this->uri->segment(3).'/board_id/'.$this->uri->segment(5).'/page/'.$pages);
                    exit;
                }
            } else {
                $data['views'= $this->board_m->get_view($this->uri->segment(3), $this->uri->segment(5));
                
                $this->load->view('board/modify_v'$data);
            }
        }
    }
     
    cs




     입력 메서드인 write()와 수정 메서드인 modify()를 비교해보면 약간의 소스 수정만으로 처리가 가능한 것을 알 수 있습니다.


     이제 모델을 살펴봅니다. 글 수정 모델 부분도 입력과 비슷합니다. insert_board() 함수를 복사하여 modify_board()를 만들고 수정합니다.


     * board_m.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
     
    <?php
    if (!defined('BASEPATH'))
        exit('No direct script access allowed');
     
    /**
     * 공통 게시판 모델
     */
     
    class Board_m extends CI_Model {
        
     
        ....
     
     
        /**
         * 게시물 수정
         * 
         * @param array $arrays 테이블 명, 게시물 번호, 게시물 제목, 게시물 내용
         * @return boolean 성공 여부
         */
        function modify_board($arrays) {
            $modify_array = array(
                'subject' => $arrays['subject'],
                'contents' => $arrays['contents']
            );
            
            $where = array(
                'board_id' => $arrays['board_id']
            );
            
            $result = $this->db->update($arrays['table'], $modify_array$where);
            
            return $result;
        }
    }
     
    cs




     수정에서는 INSERT가 UPDATE로 바뀌고 where 절이 추가되었습니다. 간단하게 수정 처리가 끝났습니다.


     뷰를 살펴보겠습니다. 수정 뷰도 입력 뷰와 다른 점은 폼 태그의 value가 추가되어 내용이 보여진다는 점입니다.


     * modify_v.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
     
    <!DOCTYPE html>
    <html>
        <head>
            <meta charset="UTF-8"/>
            <meta name="apple-mobile-web-app-capable" content="yes" />
            <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no" />
            <title>CodeIgniter</title>
            <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
            <link type="text/css" rel="stylesheet" href="/bbs/include/css/bootstrap.css" />
            <script>
                $(document).ready(function() {
                    $("#write_btn").click(function() {
                        if ($("#input01").val() == '') {
                            alert('제목을 입력해 주세요.');
                            $("#input01").focus();
                            return false;
                        } else if ($("#input02").val() == '') {
                            alert('내용을 입력해 주세요.');
                            $("#input02").focus();
                            return false;
                        } else {
                            $("#write_action").submit();
                        }
                    });
                });
           </script>
        </head>
        <body>
            <div id="main">
                <header id="header" data-role="header" data-position="fixed">
                    <blockquote>
                        <p>
                            만들면서 배우는 CodeIgniter
                        </p>
                        <small>실행 예제</small>
                    </blockquote>
                </header>
                <nav id="gnb">
                    <ul>
                        <li>
                            <a rel="external" href="/bbs/<?php echo $this -> uri -> segment(1); ?>/lists/<?php echo $this -> uri -> segment(3); ?>"> 게시판 프로젝트 </a>
                        </li>
                    </ul>
                </nav>
                <article id="board_area">
                    <header><h1></h1></header>
                    <form class="form-horizontal" method="post" action="" id="write_action">
                        <fieldset>
                            <legend>게시물 수정</legend>
                            <div class="control-group">
                                <label class="control-label" for="input01">제목</label>
                                <div class="controls">
                                    <input type="text" class="input-xlarge" id="input01" name="subject"
                                        value="<?php echo $views->subject; ?>" />
                                </div>
                                <label class="control-label" for="input02">내용</label>
                                <div class="controls">
                                    <textarea class="input-xlarge" id="input02" name="contents" rows="5">
                                        <?php echo $views->contents;?>
                                    </textarea>
                                </div>
                                
                                <div class="form-actions">
                                    <button type="submit" class="btn btn-primary" id="write_btn"> 수정 </button>
                                    <button class="btn" onclick="document.location.reload()">취소</button>
                                </div>
                            </div>
                        </fieldset>
                    </form>
                </article>
                <footer id="footer">
                    <dl>
                        <dt>
                            <a class="azubu" href="http://www.cikorea.net/" target="blank"> CodeIgniter 한국 사용자포럼 </a>
                        </dt>
                        <dd>
                            Copyright by <em class="black">Palpit</em>.
                        </dd>
                    </dl>
                </footer>
            </div>
        </body>
    </html>
     
    cs



     

     


















    4.6 삭제 기능 추가하기



     * board.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
    if (!defined('BASEPATH'))
        exit('No direct script access allowed');
    /**
     *  게시판 메인 컨트롤러
     */
     
    class Board extends CI_Controller {
     
     
        ......
     
     
        /**
         * 게시물 삭제
         */
         
        function delete() {
            echo '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />';
     
            $this->load->helper('alert');
            
            $return = $this->board_m->delete_content($this->uri->segment(3), $this->uri->segment(5));
            
            if ( $return ) {
                alert('삭제되었습니다.''bbs/board/lists/'.$this->uri->segment(3).'/page/'.$this->uri->segment(7));
                exit;
            } else {
                alert('삭제 실패하였습니다.''bbs/board/view/'.$this->uri->segment(3).'/board_id/'.$this->uri->segment(5).'/page/'.$this->uri->segment(7));
                exit;
            }
            
        }
    }
     
    cs






     * board_m.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
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
     
    <?php
    if (!defined('BASEPATH'))
        exit('No direct script access allowed');
     
    /**
     * 공통 게시판 모델
     */
     
    class Board_m extends CI_Model {
        function __construct() {
            parent::__construct();
        }
     
        function get_list($table = 'ci_board'$type = ''$offset = ''$limit = ''$search_word = '') {
     
            $sword = '';
     
            if ($search_word != '') {
                // 검색어 있을 경우
                $sword = ' WHERE subject like "%' . $search_word . '%" or contents like "%' . $search_word . '%" ';
            }
     
            $limit_query = '';
     
            if ($limit != '' OR $offset != '') {
                // 페이징이 있을 경우 처리
                $limit_query = ' LIMIT ' . $offset . ', ' . $limit;
            }
     
            $sql = "SELECT * FROM " . $table . $sword . " ORDER BY board_id DESC " . $limit_query;
            $query = $this -> db -> query($sql);
     
            if ($type == 'count') {
                $result = $query -> num_rows();
            } else {
                $result = $query -> result();
            }
     
            return $result;
        }
     
        /**
         * 게시물 상세보기 가져오기
         *
         * @param string $table 게시판 테이블
         * @param string $id 게시물 번호
         * @return array
         */
        function get_view($table$id) {
            // 조횟수 증가
            $sql0 = "UPDATE " . $table . " SET hits = hits + 1 WHERE board_id='" . $id . "'";
            $this -> db -> query($sql0);
     
            $sql = "SELECT * FROM " . $table . " WHERE board_id = '" . $id . "'";
            $query = $this -> db -> query($sql);
     
            // 게시물 내용 반환
            $result = $query -> row();
     
            return $result;
     
        }
        
        /**
         * 게시물 입력
         * 
         * @param array $arrays 테이블 명, 게시물 제목, 게시물 내용 1차 배열
         * @return boolean 입력 성공여부
         */
        function insert_board($arrays) {
            $insert_array = array(
                'board_pid' => 0,
                'user_id' => 'advisor',
                'user_name' => 'palpit',
                'subject' => $arrays['subject'],
                'contents' => $arrays['contents'],
                'reg_date' => date("Y-m-d H:i:s")
            );
            
            $result = $this->db->insert($arrays['table'], $insert_array);
            
            return $result;
        }
        
        /**
         * 게시물 수정
         * 
         * @param array $arrays 테이블 명, 게시물 번호, 게시물 제목, 게시물 내용
         * @return boolean 성공 여부
         */
        function modify_board($arrays) {
            $modify_array = array(
                'subject' => $arrays['subject'],
                'contents' => $arrays['contents']
            );
            
            $where = array(
                'board_id' => $arrays['board_id']
            );
            
            $result = $this->db->update($arrays['table'], $modify_array$where);
            
            return $result;
        }
        
        /**
         * 게시물 삭제
         * 
         * @param string $table 테이블 명
         * @param string $no 게시물 번호
         * @return boolean 성공 여부
         * 
         */
        function delete_content($table$no) {
            $delete_array = array(
                'board_id' => $no
            );
            
            $result = $this->db->delete($table$delete_array);
            
            return $result;
        }
    }
     
    cs




     



















    * 이 포스트는 서적 '만들면서 배우는 CodeIgniter 프레임워크'를 참고하여 작성하였습니다

    댓글

Designed by Tistory.