[CI] Create

Grace Goh·2023년 4월 2일
0

PHP

목록 보기
12/19
# controllers/board.php


class Board extends CI_Controller
{

    // validation을 쓰려면 컨트롤러에도 __construct()가 있어야.
    public function __construct()
    {
        parent::__construct();
        $this->load->library('form_validation');
        
        $this->load->model('board_model');
        // $this->load->model('board_model', 'board'); 
        // 별칭으로 만들 수 있다. '대소문자' 중요.
    }


    public function index()
    {
        $this->load->view('board/list');
    }


    public function create()
    {
        $this->load->view('board/create');
    }


    public function store()
    {
        // 폼밸리데이션의 set_rules를 이용한다.
        $this->form_validation->set_rules('title', 'Title', 'required');
        $this->form_validation->set_rules('contents', 'Contents', 'required');

        // 실행run할 때 true이면
        if($this->form_validation->run()) {
            // store를 실행하고 board/create로 redirect한다.
            $this->board_model->store();
            redirect('/board/create');
        } else {
            echo "Error";
        }
        
    }
    
}

# views/board/create.php


<form name="rafa" action="/board/store" method="post">
    <table board="1">
        <tr>
            <th>제목</th>
            <td>
                <input type="text" name="title" value="" />
            </td>
        </tr>
        <tr>
            <th>내용</th>
            <td>
                <textarea name="contents" rows="8"></textarea>
            </td>
        </tr>
        <tr>
            <th>내용</th>
            <td>
            <th colspan="2">
                <input type="submit" value=" 저장 " />
            </th>
            </td>
        </tr>
    </table>
</form>

# models/Board_model.php


<?php
class Board_model extends CI_Model {


    public function __construct()
    {
        $this->load->database();
        $this->load->helper('url');
    }


    public function store() {

        // 배열
        $data = [
            // '컬럼명'
            'title' => $this->input->post('title'),
            'contents' => $this->input->post('contents'),
            'regdate' => date("Y-m-d H:i:s")
        ];

        // $변수 ('table'에 $data 넣겠다)
        $result = $this->db->insert('boards', $data);
        return $result;
    }
}

# application/config/database.php


$db['default'] = array(
    'dsn'    => '',
    'hostname' => 'localhost',
    'username' => 'root',
    'password' => '860609',
    'database' => 'board', # db 새로 생성시 주의
    'dbdriver' => 'mysqli',
    'dbprefix' => '',
    'pconnect' => FALSE,
    'db_debug' => (ENVIRONMENT !== 'production'),
    'cache_on' => FALSE,
    'cachedir' => '',
    'char_set' => 'utf8',
    'dbcollat' => 'utf8_general_ci',
    'swap_pre' => '',
    'encrypt' => FALSE,
    'compress' => FALSE,
    'stricton' => FALSE,
    'failover' => array(),
    'save_queries' => TRUE,
);

출처 https://www.youtube.com/watch?v=TXHWW4dvFzo

profile
Español, Inglés, Coreano y Python

0개의 댓글