Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Contents

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 = 3306

The 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.

LineWhat it means
hostnameThe database server address
databaseThe database name
username, passwordThe user and password
DBDriverThe driver: MySQLi, Postgre, SQLite3, SQLSRV
portThe server port, usually 3306 for MySQL

Creating the database

The database itself is created with a spark command:

php spark db:create blog

The 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']; // 2

The 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 --show

The 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.

Thanks for reading!

Donate to the site — we work hard for you.