About Lesson
Database Configuration
CodeIgniter has a config file that lets you save your database connection values. The config file is located at app/Config/Database.php. You can also set database connection values in the .env file.
app/Config/Database.php
public $default = [ 'DSN' => '', 'hostname' => 'localhost', 'username' => 'root', 'password' => '', 'database' => 'database_name', 'DBDriver' => 'MySQLi', 'DBPrefix' => '', 'pConnect' => TRUE, 'DBDebug' => TRUE, 'cacheOn' => FALSE, 'cacheDir' => '', 'charset' => 'utf8', 'DBCollat' => 'utf8_general_ci', 'swapPre' => '', 'encrypt' => FALSE, 'compress' => FALSE, 'strictOn' => FALSE, 'failover' => [], ];
Configuring With .env File
You can also save your configuration values within a .env file with the current server’s database settings.
database.default.username = 'root'; database.default.password = ''; database.default.database = 'ci4';
Connecting to your Database
You can connect to your database by adding this line of code in any function where it is needed, or in your class constructor to make the database available globally in that class.
$db = ConfigDatabase::connect();
Connecting with Custom Settings
You can pass in an array of database settings instead of a group name to get a connection that uses your custom settings.
$custom = [ 'DSN' => '', 'hostname' => 'localhost', 'username' => '', 'password' => '', 'database' => '', 'DBDriver' => 'MySQLi', 'DBPrefix' => '', 'pConnect' => false, 'DBDebug' => (ENVIRONMENT !== 'production'), 'cacheOn' => false, 'cacheDir' => '', 'charset' => 'utf8', 'DBCollat' => 'utf8_general_ci', 'swapPre' => '', 'encrypt' => false, 'compress' => false, 'strictOn' => false, 'failover' => [], 'port' => 3306, ]; $db = ConfigDatabase::connect($custom);