Connecting Database
×

Connecting Database

2725

  • The database configuration enables to define one or more database connections that can be used by the application.
  • The database configuration is done by editing the application/config/database.php file.

Related Topics:

Helpers in Codeigniter
Codeigniter Interview Questions

Connecting Database:

Open the file database.php which contains the following code initially.

database.php

<?php
defined('BASEPATH') OR exit('No direct script access allowed');
$active_group = 'default';
$query_builder = TRUE;

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

Explanation:

  • $active_group is used to connect the application to more than one or more than one database. By default, it connects the application to the default group.
  • $active_group = 'default';

    To connect with another group, just change the value of the $active_group variable. If you want to connect with more than one environment, give the name of all them separated by a comma.

    $active_group = 'db1,db2,….';
  • hostname is the name of the host of your database server. In the case of the local server, its value is localhost.
  • username is the username used to connect to the database. In the case of the local server, its value is root.
  • password is the password used to connect to the database. In the case of the local server, its value is empty ' '.
  • database is the name of the database which you want to connect to your application.
  • dbdriver is used to change the driver. Currently, its value is MySQLi. It can be cubrid, ibase, mssql, MySQL, MySQLi, oci8, odbc, pdo, postgre, SQLite, SQLite3, SQLsrv.

You do not need to change other parameters.


Loading the database:

The database can be loaded in two ways.

1 Automatic loading: In this loading, we use the application/config/autoload.php file. Open this file and write the following line:

$autoload['libraries'] = array('database');

Related Topics:

Views in Codeigniter
Models in Codeigniter

2 Manual loading: This loading is done in the controller which you are using for application working. Open your controller file write the following line.

$this->load->database();

If you want to load a specific database, then pass the name as a parameter in the database() method.

$this->load->database('group_name');

Where group_name is the name of a group of the database that you want to connect.



Best WordPress Hosting


Share:


Discount Coupons

Get a .COM for just $6.98

Secure Domain for a Mini Price



Leave a Reply


Comments
    Waiting for your comments