Trong CodeIgniter 3, Database Library là thư viện cốt lõi giúp bạn kết nối và thao tác với cơ sở dữ liệu một cách đơn giản. Dưới đây là hướng dẫn chi tiết cách sử dụng Database Library trong CI3:


✅ 1. Cấu hình database

Mở file:

application/config/database.php

Điền thông tin kết nối:

$db['default'] = array(
    'dsn'   => '',
    'hostname' => 'localhost',
    'username' => 'ten_user_db',
    'password' => 'mat_khau',
    'database' => 'ten_database',
    'dbdriver' => 'mysqli', // hoặc 'pdo', 'postgre'...
    'dbprefix' => '',
    'pconnect' => FALSE, // dùng kết nối liên tục (nên để FALSE)
    'db_debug' => (ENVIRONMENT !== 'production'),
    'cache_on' => FALSE,
    'cachedir' => '',
    'char_set' => 'utf8',
    'dbcollat' => 'utf8_general_ci',
);

✅ 2. Tải thư viện database

Tự động (khuyên dùng):

Mở file:

application/config/autoload.php

Tìm dòng:

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

→ Sửa thành:

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

Hoặc thủ công trong controller hoặc model:

$this->load->database();

✅ 3. Truy vấn với Database Library

Bạn có thể truy vấn bằng Active Record (Query Builder) hoặc raw SQL.

▶️ SELECT (truy vấn dữ liệu)

$query = $this->db->get('users'); // SELECT * FROM users
$result = $query->result();       // Kết quả dạng object
// Có điều kiện
$this->db->where('status', 1);
$query = $this->db->get('users');

▶️ INSERT

$data = array(
    'username' => 'admin',
    'email' => '[email protected]'
);
$this->db->insert('users', $data);

▶️ UPDATE

$data = array('email' => '[email protected]');
$this->db->where('id', 5);
$this->db->update('users', $data);

▶️ DELETE

$this->db->where('id', 5);
$this->db->delete('users');

✅ 4. Raw Query (nếu cần)

$query = $this->db->query("SELECT * FROM users WHERE status = 1");
$result = $query->result_array(); // trả về mảng

✅ 5. Một số hàm hữu ích

Mục đíchCú pháp
Lấy ID vừa insert$this->db->insert_id();
Đếm dòng$query->num_rows();
Escape dữ liệu thủ công$this->db->escape($value);
Gộp nhiều điều kiện$this->db->where(['status'=>1, 'type'=>2])
Join bảng$this->db->join('profile', 'profile.user_id = users.id')

✅ 6. Ví dụ đầy đủ:

public function get_active_users() {
    $this->db->select('id, username, email');
    $this->db->from('users');
    $this->db->where('status', 1);
    $this->db->order_by('id', 'DESC');
    $query = $this->db->get();
    return $query->result_array();
}