Codeigniter Connect Your Database

Codeigniter Connect Your Database – This database reference is used to connect database. There are two ways to connect to the database. Here in this tutorial, we are going to explain the both ways to connect your database.

Connect your database | Example.


There are following functions available in connect to your database. Now we will explain one by one.

  • 1. Automatically connecting.
  • 2. Manually connecting.
  • 3. Connecting to multiple databases.
  • 4. Reconnecting / Keeping the Connection Alive.
  • 5. Manually closing the Connection.

1. Automatically connecting

The auto connect feature will load and represent the database class with every page load. To enable ‘auto connecting’. add the word database to the library array.

File path where we load auto connect feature:-


2. Manually connecting

If any particular page requires database connectivity then you can manually connect to your database by adding this line of code.

Manualaly database connection code:-


Manually connecting to a database

The first parameter of the function can optionally be used to specify a particular database group from your config file.


To connect manually to a desired database you can pass an array of values.

Syntax of manually connecting to a database:-

$config['hostname'] = 'localhost';
$config['username'] = 'username';
$config['password'] = 'password';
$config['database'] = 'database_name';
$config['dbdriver'] = 'mysqli';
$config['dbprefix'] = '';
$config['pconnect'] = FALSE;
$config['db_debug'] = TRUE;
$config['cache_on'] = FALSE;
$config['cachedir'] = '';
$config['char_set'] = 'utf8';
$config['dbcollat'] = 'utf8_general_ci';

3. Connecting to multiple databases

If you need to connect more than one database then you can do like this:-

Syntax of connecting multiple database:-


4. Reconnecting / Keeping the Connection alive

If the database server idle timeout is set to some limit while you are doing some heavy PHP lifting, you should consider pinging the server by using the reconnect() method.

Syntax of reconnecting / keeping the connection alive:-


5. Manually closing the connection

While codeigniter takes care of closing your database connections still you can explicitly close the connection.

Syntax of manually closing the connection:-



Add Comment

📖 Read More