ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [CodeIgniter] 데이터베이스(Database) 시작하기
    프로그래밍/CodeIgniter 2018. 4. 22. 20:03

    ▶CodeIgniter 데이터베이스(Database) 시작하기



    ▶설명



    이제 간단하지만, MVC 모델 전부를 설명했습니다.


    이번에는 모델(Models)에서 데이터베이스(Database)에 있는 데이터를 가져오는 간단한 예제를 통해,

    데이터베이스를 연결하는 기본적인 방법을 알아보도록 하겠습니다.

    * 간단한 방법만을 정리했기 때문에, 상세한 방법을 알고 싶으시면 [링크]를 참고하여 주시기 바랍니다.


    이전에 모델(Models) 예제를 기준으로 예제를 작성하도록 하겠습니다.


    ▶준비하기



    데이터베이스(Database)에 members 테이블 추가 및 데이터 입력

    -- 테이블 추가
    CREATE TABLE `members` (
        `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
        `name` varchar(128) NOT NULL,
        PRIMARY KEY (`id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
    -- 데이터 추가
    INSERT INTO members (name) VALUES ('Edward') , ('Alex');


    테이블 데이터 확인

     id

    name 

     1 

    Edward 

      2 

    Alex 



    ▶예제 (Example)



    데이터베이스(Database) 값 설정

    application/config/database.php

    <?php
    defined('BASEPATH') OR exit('No direct script access allowed');
    // ...... Database Setting Comment
    
    $active_group = 'default';
    $query_builder = TRUE;
    
    $db['default'] = array(
        'dsn'	=> '',
        'hostname' => 'localhost',
        'username' => 'yourname',
        'password' => 'yourpassword',
        'database' => 'yourdb',
        '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
    );

    db배열 안에 데이터베이스(Database) 연결 값을 설정합니다.


    모델(Models) 수정

    application/models/Member_model.php

    <?php
    defined('BASEPATH') OR exit('No direct script access allowed');
        
    class Member_model extends CI_Model {
        
        public function __construct()
        {
            parent::__construct();
        }
    
        public function GetMembers()
        {
            $this->load->database();
            $result = $this->db->query('SELECT id, name FROM members')->result();
            $this->db->close();
    
            return $result;
        }
    }
    • 컨트롤러(Controllers)에서 모델(Models)을 사용하는 부분은 변동 사항이 없습니다.
    • 13번째줄 : 데이터베이스(Database) 설정에 맞추어 데이터베이스를 로드합니다.
      * 데이터베이스 설정 파일에서 active_group에 설정된 데이터베이스 정보로 연결해줍니다.
    • 14번째줄 : 데이터베이스(Database)에 쿼리를 보내고 그 결과를 객체(Object)로 반환 해 주는 코드입니다.
    • 15번째줄 : 보통 데이터베이스(Database)에 대한 연결을 자동으로 끊어주지만, 해당 코드는 수동으로 데이터베이스(Database) 연결을 끊어주는 코드입니다.


    뷰(Views) 수정

    application/views/Tutorial/members.php

    <!DOCTYPE html>
    <html lang="ko">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <title>Member</title>
    </head>
    <body>
        <table>
            <thead>
                <tr>
                    <th>ID</th>
                    <th>Name</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach($members as $member) :?>
                    <tr>
                        <td><?=$member->id?></td>
                        <td><?=$member->name?></td>
                    </tr>
                <?php endforeach ?>
            </tbody>
        </table>
    </body>
    </html>


    확인

    http://localhost/ci/Tutorial/Members


    댓글

Designed by Tistory.