프레임워크/코드이그나이터(Codeigniter)

코드이그나이터 4 데이터베이스 연결방법

마루의 일상 2021. 11. 29. 16:28
728x90
반응형

코드이그나이터 4에서 데이터베이스를 연결하기 위해서는 db설정을 해야 합니다.

원래 기본적인 소스에는 port 관련 변수가 설정되어 있지 않으나 port를 변경해야 할 경우는 port를 추가하시면 됩니다.

 

app/Config/Database.php에 $default에 설정을 합니다.

<?php

namespace Config;

use CodeIgniter\Database\Config;

/**
 * Database Configuration
 */
class Database extends Config
{
    public $filesPath = APPPATH . 'Database' . DIRECTORY_SEPARATOR;

    public $defaultGroup = 'default';

    public $default = [
        'DSN'      => '',
        'hostname' => 'localhost',
        'username' => 'root',
        'password' => 'root',
        'database' => 'ci4tutorial',
        'DBDriver' => 'MySQLi',
        'DBPrefix' => '',
        'pConnect' => false,
        'DBDebug'  => (ENVIRONMENT !== 'production'),
        'charset'  => 'utf8',
        'DBCollat' => 'utf8_general_ci',
        'swapPre'  => '',
        'encrypt'  => false,
        'compress' => false,
        'strictOn' => false,
        'failover' => [],
        'port'     => 3306,
    ];

    public $image = [
        'DSN'      => '',
        'hostname' => 'localhost',
        'username' => 'root',
        'password' => 'root',
        'database' => 'ci4image',
        'DBDriver' => 'MySQLi',
        'DBPrefix' => '',
        'pConnect' => false,
        'DBDebug'  => (ENVIRONMENT !== 'production'),
        'charset'  => 'utf8',
        'DBCollat' => 'utf8_general_ci',
        'swapPre'  => '',
        'encrypt'  => false,
        'compress' => false,
        'strictOn' => false,
        'failover' => [],
        'port'     => 3306,
    ];

    public function __construct()
    {
        parent::__construct();

        if (ENVIRONMENT === 'testing') {
            $this->defaultGroup = 'tests';
        }
    }
}

db 연결하는 방법으로는 $db = \Config\Database::connect();으로 연결하면 됩니다.

괄호 안에 값이 없을 경우 기본정보로 연결됩니다.

$db = \Config\Database::connect();

이 방법 외에 $db = db_connect(); 로 사용 가능합니다.

\system\Common.php에 db_connect가 선언되어 있습니다. 

if (! function_exists('db_connect')) {
    /**
     * Grabs a database connection and returns it to the user.
     *
     * This is a convenience wrapper for \Config\Database::connect()
     * and supports the same parameters. Namely:
     *
     * When passing in $db, you may pass any of the following to connect:
     * - group name
     * - existing connection instance
     * - array of database configuration values
     *
     * If $getShared === false then a new connection instance will be provided,
     * otherwise it will all calls will return the same instance.
     *
     * @param array|ConnectionInterface|string|null $db
     *
     * @return BaseConnection
     */
    function db_connect($db = null, bool $getShared = true)
    {
        return Database::connect($db, $getShared);
    }
}

만약 연결 db를 다른 걸로 쓰고 싶은 경우는 아래처럼 변경합니다.

$db = \Config\Database::connect('변경할 데이터베이스 변수');
예) $db = \Config\Database::connect('image'); 데이터베이스 변수명을 변경 하면됩니다.

app\Config\Database.php에 설정되어 있는 변수

데이터 베이스 연결 방법이었습니다.

감사합니다.

 

728x90
반응형