CodeIgniter Basic Tutorial
Performance & Utilities
CodeIgniter Advanced
To interact with databases in CodeIgniter, we need to configure a MySQL connection.
CodeIgniter provides a simple and secure way to connect and run queries using the Database Library.
👉 Database connection settings are managed inside:
application/config/database.php
Go to:
application/config/database.php
You will see an array named $db['default']
which holds database settings.
Example configuration for MySQL:
$db['default'] = array( 'dsn' => '', 'hostname' => 'localhost', 'username' => 'root', 'password' => '', 'database' => 'ci_tutorial', 'dbdriver' => 'mysqli', 'dbprefix' => '', 'pconnect' => FALSE, 'db_debug' => (ENVIRONMENT !== 'production'), 'cache_on' => FALSE, 'cachedir' => '', 'char_set' => 'utf8', 'dbcollat' => 'utf8_general_ci', );
localhost
)root
by default in XAMPP/WAMP)ci_tutorial
)mysqli
for MySQLi)FALSE
recommended)Instead of loading DB manually each time, you can autoload it.
Open:
application/config/autoload.php
Add database
inside libraries:
$autoload['libraries'] = array('database');
Now database will load automatically.
Create a controller and fetch data to confirm connection.
Example: Welcome.php
class Welcome extends CI_Controller { public function index() { // Fetch all users $query = $this->db->get('users'); // SELECT * FROM users $result = $query->result(); echo "<pre>"; print_r($result); echo "</pre>"; } }
👉 If your DB connection is correct, it will show the records.
CodeIgniter provides two main ways to query MySQL:
$this->db->select('name, email'); $this->db->from('users'); $query = $this->db->get(); $result = $query->result();
$query = $this->db->query("SELECT * FROM users WHERE status = 1"); $result = $query->result();