×

Database Configuration CodeIgniter

In every application, there is an important part of a database through which developers can connect an application to store users’ data and perform various functions in the database application such as inserting, updating, reading, and deleting the values. Before performing these functionalities, you have to set the database configuration in the CodeIgniter application. A CodeIgniter contains an inbuilt database.php file that allows you to set database connection values such as hostname, username, password, database, dbdriver name, etc. and this file is located at application/config/database.php.

Database Configuration CodeIgniter

Set the Default Database Configuration

The default structure of the database configuration is as follows:

$db['default'] = array (
 'dsn'     => '', 
             'hostname' => 'localhost',
             'username' => 'root',
             'password' => 'db_password',
             'database' => 'codedb',
             'dbdriver' => 'mysqli', 
             'cache_on' => FALSE,
             'cachedir' => '',
             'dbprefix' => '',
             'pconnect' => FALSE,
             'db_debug' => (ENVIRONMENT ! == 'production'),
             'swap_pre' => '', 
             'encrypt' => FALSE,
             'dbcollat' => 'utf8_general_ci',
             'char_set' => 'utf8',
             'compress' => FALSE,
             'save_queries' => TRUE,
             'failover' => array(), 
             'stricton' => FALSE
 ); 

There are the following key points available in the database.php file while connecting with the database configuration:

  1. It specifies the host location of your database. For example- localhost or IP address
  2. It defines the username of your database, such as root.
  3. As the name suggests, it is used to set the password of your database. By default, this is blank in most databases, and you can also set your own database password.
  4. It is used to specify the name of the database that you have created in phpMyAdmin, MySQL, etc.
  5. In this dbdriver, you can specify the type of databases such as MySQL, Postgre SQL, ODBC, MySQLi, and MS SQL.

It also contains some database driver such as PDO, Oracle, ODBC and PostgreSQL that require full DSN string to be connected with database.

For example:

// Oracle
 $db[ ‘default’ ][ ‘dsn’ ] = ‘//localhost/XE’;
 // PDO 
 $db[ ‘default’][ ‘dsn’ ] = ‘pgsql:host = localhost; port = 5432; dbname = database_name’; 

Failover database connection

You can also set a failover database connection when the main connection is not working. This can be achieved by setting the connection as shown below:

$db['default'] ['failover'] = array(    // if the default connection has lost, failover works
                 array(
                         'hostname' => 'localhost',
                         'username' => '',
                         'password' => '',
                         'database' => '',
                         'dbdriver' => 'mysqli', 
                         'dbprefix' => '',
                         'pconnect' => TRUE,
                         'db_debug' => TRUE,
                         'cache_on' => FALSE,
                         'cachedir' => '',
                         'char_set' => 'utf8', 
                         'dbcollat' => 'utf8_general_ci',
                         'swap_pre' => '',
                         'encrypt' => FALSE,
                         'compress' => FALSE,
                         'stricton' => FALSE 
                 ),
                 array(
                         'hostname' => 'localhost1', // provide another localhost name
                         'username' => '',
                         'password' => '',
                         'database' => '',
                         'dbdriver' => 'mysqli', 
                         'dbprefix' => '',
                         'pconnect' => TRUE,
                         'db_debug' => TRUE,
                         'cache_on' => FALSE,
                         'cachedir' => '',
                         'char_set' => 'utf8', 
                         'dbcollat' => 'utf8_general_ci',
                         'swap_pre' => '',
                         'encrypt' => FALSE,
                         'compress' => FALSE,
                         'stricton' => FALSE 
                 )
         ); 

Multiple Database Configuration

A Codeigniter also provides a suitability to add multiple database connection with a default connection that can work simultaneously in the database.php file, as follows.

//Default database configuration

$db['default'] = array(
     'dsn'       => '',
     'hostname' => 'localhost',
     'username' => 'db_username',
     'password' => 'db_password',
     'database' => 'db_name',  // provide database name 
     '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
 ); 

//Another database configuration

$db['another_db'] = array(
     'dsn'       => '',
     'hostname' => 'localhost',
     'username' => 'db_username',
     'password' => 'db_password',
     'database' => 'db_name2', 
     '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
 ); 

// third database configuration

$db['test_db'] = array(
     'dsn'       => '',
     'hostname' => 'localhost',
     'username' => 'db_username',
     'password' => 'db_password',
     'database' => 'db_name3',
     '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
 ); 

After connecting the multiple database connection, you must to load a database in the CodeIgniter application as follows:

// load another database
 $db2 = $this->load->database(‘another_db’, TRUE); 

The first parameter contains the ‘database name’, whereas second parameter contains ‘TRUE’ to get the database object.

Similarly,

// load third database
 $db2 = $this->load->database(‘test_db’, TRUE); 

How to use multiple database in CodeIgniter?

Now, if you want to access the multiple connection by the database object, follows the given below syntax:

// for default database
 $this->db->select( ‘username’, ‘password’);
 $this->db->from(‘students’);
 $this->db->where(‘id’, 35);
 $query = $this->db->get();
 // for another database 
 $db->select( ‘rollno’, ‘course’);
 $db->from(‘student_registraion’);
 $db->where(‘id’, 15);
 $query = $db->get(); 

How to call a database connection in the CodeIgniter application?

There are two ways to call a database connection in the application as:

It is an automatic connection that automatically loads the database library into the Codeigniter application, and this connection can be made using the application/config/autoload.php file.

Syntax

$autoload[ ‘libraries’ ] = array(‘database’);
 // or you can load database connection with other libraries
 $autoload[ ‘libraries’ ] = array(‘database’, ‘email’, ‘form_validation’); 

In manual connection, it allows you to load database connection on some page of the class controller or to access it globally for that particular class.

Syntax

$this->load->database();

What is $active_group?

A $active_group tells the system to access a globally defined database that is located in the config/database.php file. And if you want to add more active group, you can specify the database in $active_group, as shown below:

$active_group = ‘default’;  // it shows default active group
 $active_group = ‘test_db’;  // it shows test_db $active_group 

What is a Query Builder?

A Query Builder class that globally enables you to perform a query to the database by setting the $query_builder variables to TRUE/FALSE in the database configuration file. The default setting of the query builder is TRUE, and if you are not using the query builder, set it to FALSE.

$query_builder = TRUE;

Reconnecting or Keeping the connection is alive

In some situations, where the database server’s idle timeout exceeded due to heavy PHP processing in the CodeIgniter application. Therefore, you should reconnect the server by using the reconnect() method before performing further queries to your database. That way, you can keep the connection alive or reconnect it.

$this->db->reconnect();

Closing the Connection

If you want to close a database connection, you must manually close the connection by executing the following syntax-

$this->db->close();  // it close the default database connection
$this->another_db_name->close(); // it close the defined database connection 

Related Topics

Calendaring Class CodeIgniter

Calendaring Class The calendar library contains various functions that are used to create a dynamic calendar. It also enables you to pass the data to calendar cells and 100% control over the calendar...

6 minutes read.

CodeIgniter User Agent Class

User Agent Class The CodeIgniter provides a user agent class that helps to identify and collect information about the browser, mobile devices, or robots visiting your site. Besides this, it is also used...

4 minutes read.

Database Configuration CodeIgniter

In every application, there is an important part of a database through which developers can connect an application to store users’ data and perform various functions in the database application such as inserting,...

10 minutes read.

CodeIgniter Helpers

The Helpers (functions) are stored in the Helper file. It helps CodeIgniter to perform different tasks. The helper file is the collection of many functions that is used to perform specific task. It...

3 minutes read.

CodeIgniter CAPTCHA Helper

A CAPTCHA (Complete Automated Public Turning test to tell Computer and Humans Apart) helper is a function that is used in web application to check whether the user is human or machine. It...

3 minutes read.

Installation of CodeIgniter

Before installing CodeIgniter, you need to make sure that the wamp or xampp server in the system is preinstalled. The installation procedure for CodeIgniter is very easy. You can download CodeIgniter by following these...

2 minutes read.

Migration Class CodeIgniter

The CodeIgniter framework provides the migration class that helps the web developers to create and handle databases in a structured and streamlined manner. The migration classes are very useful when more than...

6 minutes read.

How to remove an index.php file from the Codeigniter URLs?

As we know, a URL in CodeIgniter is designed in such a way that it would be search engine and human friendly, too, rather than using a standard approach to create a...

2 minutes read.

CodeIgniter Form Helper

A form helper file contains different functions that works with forms. It is used to create various functionality in a form such as dropdown, radio button, password, upload, hidden data, etc. These functionalities...

12 minutes read.

CodeIgniter Creating Library

As we know, CodeIgniter has a large collection of library functions that are stored in the system/libraries folder. CodeIgniter also provides some additional functionality in library files. For example, if you want to...

3 minutes read.

CodeIgniter String Helper

The string helper file contains functions that allows separate operations with strings in CodeIgniter. Loading the String Helper Before using the string helper in the CodeIgniter application, you must load it in the controller...

7 minutes read.

CodeIgniter Shopping Cart Class

It contains the various function that enables the user to add or update, display, and delete data item from the shopping carts while browsing the site. The items added in the cart...

10 minutes read.

CodeIgniter Array Helper

The Array Helper contains some predefined functions that are used to perform the various operation with array. Load Array helper It is used to load the helper class. We can pass the helper function in the...

6 minutes read.

CodeIgniter Tutorial

What is CodeIgniter? CodeIgniter is an open-source framework for developing a dynamic web application with the use of PHP. It uses the MVC framework to develop the project, which is much...

3 minutes read.

CodeIgniter HTML Helper

The HTML helper function is used in CodeIgniter to provide various functionality, such as headings, images, links, list tags, etc. Loading the HTML Helper Before using the html helper function, you must load the...

7 minutes read.

Retrieve data from Database

Retrieve data from the Database Now we will discuss how we can retrieve data from the database that we have inserted to the employees table of the database in our previous topic “inserted...

2 minutes read.

Codeigniter Session Library

Session Library The session is an essential part of any application. It contains various functions to manage the users' status and track their activity while browsing on the site. For example,...

13 minutes read.

CodeIgniter Output class

Output class The CodeIgniter framework contains a core class that is an Output class. It  includes the various functions that are used to send the final web page to the requesting browser. In...

8 minutes read.

Update a Record CodeIgniter

Update a record In this topic, we will learn how we can update existing records in database tables. To update a record, CodeIgniter provides an update() function used with the set()...

10 minutes read.

CodeIgniter Email Class

CodeIgniter provides an e-mail library that helps to send a message from one application to another. You can create and send text messages easily in CodeIgniter application even you can set email...

9 minutes read.