[CI] Read

Grace Goh·2023년 4월 2일
0

PHP

목록 보기
13/19

먼저 리스트를 가져오는 컨트롤러를 만든다.

# controllers/Board.php


class Board extends CI_Controller {

    public function __construct()
    {
        parent::__construct();
        $this->load->library('form_validation');
        $this->load->model('board_model');
    }


    public function index()
    {
        // 데이터를 담겠다 = ...모든 데이터 가져오는 형태
        $data['articles'] = $this->board_model->getAll();
        // 이것을 리스트로 보낸다.
        $this->load->view('board/list', $data);

board_model의 getAll() 함수를 실행하면

# models/Board_model.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;
    }

    
    public function getAll() {

        // 최신순(역순)으로 출력하기
        $this->db->order_by('idx', 'desc');
        // db에서 가져오기get ('boards' 테이블을 전부 넣겠다)
        $board = $this->db->get('boards')->result();
        // var_dump($board);
        // exit;
        return $board;
    }
}

'articles'라는 키값으로 저장하는 것.

# controllers/Board.php


    public function index()
    {
        // 데이터를 담겠다 = ...모든 데이터 가져오는 형태
        $data['articles'] = $this->board_model->getAll();
        // 이것을 리스트로 보낸다.
        $this->load->view('board/list', $data);

index()에서 ['articles'] 데이터를 가져오겠다고 했기 때문에
['articles']를 index 안에서 foreach로 돌린다.



상세페이지

컨트롤러에 show()를 만든다.

# controllers/Board.php


    // idx 번호를 이용해 불러오겠다.
    public function show($idx)
    {
        // 데이터에 ['view']라는 배열을 만들어서, 모델에서 가져온다.
        $data['view'] = $this->board_model->get($idx);
        
        $this->load->view('board/show', $data);
    }

모델에 getAll()을 복사해서 get()을 만든다.

# models/Board_model.php


    public function getAll() {
    
    	$board = $this->db->get('boards')->result();
        return $board;
    }


    public function get($idx) {
    
        // CI 제공 함수. if절을 넣을 수 있다. -> 하나일 경우 row
        $board = $this->db->get_where('boards', ['idx' => $idx])->row();
        return $board;
    }

뷰를 만든다.

# views/board/show.php


<table border='1'>
    <tr>
        <th>제목</th>
        <td><?= $view->title; ?></td>
    </tr>
    <tr>
        <th>내용</th>
        <td><?= $view->contents; ?></td>
    </tr>
    <tr>
        <th>작성일</th>
        <td><?= $view->regdate; ?></td>
    </tr>
    <tr>
        <th colspan="2">
            <a href="/board">목록</a>
        </th>
    </tr>
</table>
profile
Español, Inglés, Coreano y Python

0개의 댓글