Database connection
The blog posts have to be stored somewhere — for that the site needs a database. CodeIgniter works with MySQL, PostgreSQL, SQLite and SQL Server. To connect, it only needs the server address, the database name, a user and a password.
Where the settings live
The defaults are written in the app/Config/Database.php class, in the $default property. There is no need to change that file: the settings of your own computer go into .env in the project root.
database.default.hostname = localhost
database.default.database = blog
database.default.username = root
database.default.password = secret
database.default.DBDriver = MySQLi
database.default.port = 3306The sample env already has these lines, commented out with # — remove it and enter your values. The word default is the connection name: a project may have several.
| Line | What it means |
|---|---|
hostname | The database server address |
database | The database name |
username, password | The user and password |
DBDriver | The driver: MySQLi, Postgre, SQLite3, SQLSRV |
port | The server port, usually 3306 for MySQL |
Creating the database
The database itself is created with a spark command:
php spark db:create blogThe terminal reports that the blog database has been created. The same can be done in phpMyAdmin or another MySQL tool.
Checking the connection
The db_connect() function returns the connection object. Check it in any controller:
// app/Controllers/Home.php
public function index(): string
{
$db = db_connect();
return 'Server version: ' . $db->getVersion();
}Open the home page: if the connection works, a line like "Server version: 8.0.36" appears. On failure CodeIgniter shows a page describing the error.
A simple query
The same object runs SQL queries:
$db = db_connect();
$row = $db->query('SELECT 1 + 1 AS total')->getRowArray();
echo $row['total']; // 2The query() method sends the query, and getRowArray() returns the first row of the result as an array. You will rarely write SQL by hand: migrations create tables and models work with records — the next lessons cover them.
The table list
php spark db:table --showThe command prints the table names of the database. While the database is empty, so is the list.
Common mistake
The message "Unable to connect to the database" means one of the connection lines is wrong or the MySQL server is not running. Check that the lines in .env do not start with #, that the database name matches the one you created, and that the password has no stray spaces. The detailed error text is visible only in development mode.