Posted by Arjun on Friday 19th September 2014

How to connect to MySQL database in CodeIgniter?

CodeIgniter Database How to MySQL connect to

Yesterday someone asked me to make a tutorial about Connecting to Database in CodeIgniter Framework. In order to make connection to database in Ci , we need to do only few configuration changes in your database.php config file which is located at application / config / database.php.

$db['default']['hostname'] = "localhost"; // set you host name
$db['default']['username'] = "root"; // set MySQL username 
$db['default']['password'] = ""; // set MySQL userpassword
$db['default']['database'] = "your_database_name"; // set your database name
$db['default']['dbdriver'] = "mysql"; 
$db['default']['dbprefix'] = "";
$db['default']['pconnect'] = TRUE;
$db['default']['db_debug'] = FALSE;
$db['default']['cache_on'] = FALSE;
$db['default']['cachedir'] = "";
$db['default']['char_set'] = "utf8";
$db['default']['dbcollat'] = "utf8_general_ci";
$db['default']['swap_pre'] = "";
$db['default']['autoinit'] = TRUE;
$db['default']['stricton'] = FALSE;

After making changes to database.php config file, we can connect to the database in two ways.
First one is Automatic loading, to do this just go to autoload.php file which is located at application/ config / database.php file. Then add 'database' to $autoload['libraries'] = array() array.

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

Another way of loading is manual loading with $this->load->database() method. place this line to load database in your controller contractor or with in the method(s).

$db = $this->load->database();
$query = $db->get('users');  // users is table anme
var_dump($query);

Sometimes you may get fallowing error i got this error message with net4india shared hosting environment

Unable to connect to your database server using the provided settings.

Filename: core/Loader.php

Line Number: 346

In order to fix this issue , i simple changed config values of pconnect to false.

$db['default']['pconnect'] = FALSE;

That's it for database connecting and loading in CI, if you have any issues , let me know via comments.