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:
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',
);
Mở file:
application/config/autoload.php
Tìm dòng:
$autoload['libraries'] = array();
→ Sửa thành:
$autoload['libraries'] = array('database');
$this->load->database();
Bạn có thể truy vấn bằng Active Record (Query Builder) hoặc raw SQL.
$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');
$data = array(
'username' => 'admin',
'email' => '[email protected]'
);
$this->db->insert('users', $data);
$data = array('email' => '[email protected]');
$this->db->where('id', 5);
$this->db->update('users', $data);
$this->db->where('id', 5);
$this->db->delete('users');
$query = $this->db->query("SELECT * FROM users WHERE status = 1");
$result = $query->result_array(); // trả về mảng
Mục đích | Cú 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') |
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();
}