반응형

이번엔 게시판에 글을 등록하는 작업을 해보자. 우선 게시판 리스트에 글쓰기 버튼을 달아 보도록 하자.

 

/app/Views/board_list.php

 

    <table class="table">
        <thead>
            <tr>
            <th scope="col">번호</th>
            <th scope="col">글쓴이</th>
            <th scope="col">제목</th>
            <th scope="col">등록일</th>
            </tr>
        </thead>
        <tbody id="board_list">
            <?php
            foreach($list as $ls){
            ?>
                <tr>
                    <th scope="row"><?php echo $ls->bid;?></th>
                    <td><?php echo $ls->userid;?></td>
                    <td><a href="/boardView/<?php echo $ls->bid;?>"><?php echo $ls->subject;?></a></td>
                    <td><?php echo $ls->regdate;?></td>
                </tr>
            <?php }?>
        </tbody>
        </table>

        <p style="text-align:right;">
            <a href="/boardWrite"><button type="button" class="btn btn-primary">등록</button><a>
        </p>

요렇게 나오면 된다. 버튼을 누르면 게시판 등록 페이지가 나타난다.

 

/app/Views/board_write.php

 

    <form method="post" action="<?= site_url('/writeSave') ?>" enctype="multipart/form-data">
        <div class="mb-3">
        <label for="exampleFormControlInput1" class="form-label">제목</label>
            <input type="text" name="subject" class="form-control" id="exampleFormControlInput1" placeholder="제목을 입력하세요." value="">
        </div>
        <div class="mb-3">
        <label for="exampleFormControlTextarea1" class="form-label">내용</label>
        <textarea class="form-control" id="exampleFormControlTextarea1" name="content" rows="3"></textarea>
        </div>
        <br />
        <button type="submit" class="btn btn-primary">등록</button>
    </form>

 

action부분을 잘 봐두자. 기존과는 조금 다르다. 아래와 같이 뜨면 된다.

간단하게 제목과 내용만 입력하는 게시판이다.이제 등록 버튼을 클릭하면 등록이 되도록 작업해보자. 우선 라우트다.

 

/app/Config/Routes.php

 

<?php

namespace Config;

// Create a new instance of our RouteCollection class.
$routes = Services::routes();

// Load the system's routing file first, so that the app and ENVIRONMENT
// can override as needed.
if (is_file(SYSTEMPATH . 'Config/Routes.php')) {
    require SYSTEMPATH . 'Config/Routes.php';
}

/*
 * --------------------------------------------------------------------
 * Router Setup
 * --------------------------------------------------------------------
 */
$routes->setDefaultNamespace('App\Controllers');
$routes->setDefaultController('Home');
$routes->setDefaultMethod('index');
$routes->setTranslateURIDashes(false);
$routes->set404Override();
// The Auto Routing (Legacy) is very dangerous. It is easy to create vulnerable apps
// where controller filters or CSRF protection are bypassed.
// If you don't want to define all routes, please use the Auto Routing (Improved).
// Set `$autoRoutesImproved` to true in `app/Config/Feature.php` and set the following to true.
// $routes->setAutoRoute(false);

/*
 * --------------------------------------------------------------------
 * Route Definitions
 * --------------------------------------------------------------------
 */

// We get a performance increase by specifying the default
// route since we don't have to scan directories.
$routes->get('/', 'Home::index');
$routes->get('/board', 'Board::list');
$routes->get('/boardWrite', 'Board::write');
$routes->match(['get', 'post'], 'writeSave', 'Board::save');
$routes->get('/boardView/(:num)', 'Board::view/$1');

/*
 * --------------------------------------------------------------------
 * Additional Routing
 * --------------------------------------------------------------------
 *
 * There will often be times that you need additional routing and you
 * need it to be able to override any defaults in this file. Environment
 * based routes is one such time. require() additional route files here
 * to make that happen.
 *
 * You will have access to the $routes object within that file without
 * needing to reload it.
 */
if (is_file(APPPATH . 'Config/' . ENVIRONMENT . '/Routes.php')) {
    require APPPATH . 'Config/' . ENVIRONMENT . '/Routes.php';
}

컨트롤러를 수정해보자.

 

/app/Controllers/Board.php

 

<?php

namespace App\Controllers;
use App\Models\BoardModel;//사용할 모델을 반드시 써줘야한다.

class Board extends BaseController
{
    public function list()
    {
        $db = db_connect();
        $query = "select * from board order by bid desc";
        $rs = $db->query($query);
        $data['list'] = $rs->getResult();//결과값 저장
        return render('board_list', $data);//view에 리턴
    }

    public function write()
    {
        return render('board_write');  
    }

    public function save()
    {
        $db = db_connect();
        $subject=$this->request->getVar('subject');
        $content=$this->request->getVar('content');

        $sql="insert into board (userid,subject,content) values ('test','".$subject."','".$content."')";
        $rs = $db->query($sql);
        return $this->response->redirect(site_url('/board'));
    }

    public function view($bid = null)
    {
        $db = db_connect();
        $query = "select * from board where bid=".$bid;
        $rs = $db->query($query);
        $data['view'] = $rs->getRow();

        return render('board_view', $data);  
    }
}

save 부분을 보자. 별다른건 없다. 변수를 받는 방식이 조금 바뀌었을뿐. 변수를 받아서 디비에 저장하고 다시 리스트로 돌아가는 로직이다. 이렇게 저장하고 테스트해보자.

 

게시판 리스트에 정상적으로 등록한 글이 나타난다면 성공이다. 안되면 처음부터 다시해보자. 이게 안되면 진도를 나갈 수가 없다. 

 

다음시간엔 글 수정하는 걸 해보자.

 

반응형

+ Recent posts