Codeigniter 4 – Connecting to Database with Example
Connecting to a Database
- Use the db_connect() function to connect to a database.
Example:
$db = db_connect();
Specifying the Database Group
- Use the db_connect() function with the database group name to connect to a specific database.
Example:
$db = db_connect('my_group');
Specifying the Database Configuration
- Use the db_connect() function with the database configuration array to connect to a database.
Example:
$config = [
'DSN' => '',
'hostname' => 'localhost',
'username' => 'root',
'password' => '',
'database' => 'my_database',
'DBDriver' => 'MySQLi',
];
$db = db_connect($config);
Using the Database Object
- Use the $db object to execute queries and retrieve data.
Example:
$db->query('SELECT * FROM my_table');
Closing the Database Connection
- Use the db_close() function to close the database connection.
Example:
db_close($db);
Using the Query Builder
- Use the db_connect() function to connect to a database and then use the query builder to execute queries.
Example:
$db = db_connect();
$db->table('my_table')->get();
Using the Active Record Pattern
- Use the db_connect() function to connect to a database and then use the active record pattern to execute queries.
Example:
$db = db_connect();
$db->my_table->get();
I hope this helps! Let me know if you have any further questions or need more information.
Note: The Database class in CodeIgniter 4 provides a powerful and flexible way to interact with your database. It supports multiple database drivers, including MySQL, PostgreSQL, and SQLite.