CodeIgniter connect database

codeigniter

To connect to a database in CodeIgniter, follow these steps:

  1. Open the application/config/database.php file and set your database settings.
$db['default'] = array(
  'dsn'   => '',
  'hostname' => 'localhost',
  'username' => 'your_username',
  'password' => 'your_password',
  'database' => 'your_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
);
  1. In your controller, load the database library:
$this->load->database();

This will connect to the database using the settings you specified in the database.php file.

  1. You can now use the database library to perform various operations on the database. For example, to run a SELECT query, you can use the $this->db->get() method:
$query = $this->db->get('my_table');

This will execute the following SQL query:

SELECT * FROM my_table
  1. To run other types of queries, you can use the following methods:
  • $this->db->insert(): Insert a new row into a table.
  • $this->db->update(): Update existing rows in a table.
  • $this->db->delete(): Delete rows from a table.

For more information on working with databases in CodeIgniter, you can check out the official documentation: https://codeigniter.com/user_guide/database/index.html