Connect to the database
Set these in .env:
database.default.hostname = localhostdatabase.default.database = ci4_blogdatabase.default.username = rootdatabase.default.password =database.default.DBDriver = MySQLi
Get a connection with $db = db_connect(); (models connect automatically).
Query Builder — reading
Start with $db->table('posts') and chain:
where('status', 'published'),orWhere(),whereIn('id', [1, 2])like('title', 'php'),orderBy('id', 'DESC'),limit(10)join('users', 'users.id = posts.user_id')- End with
get()->getResultArray()(rows),get()->getRowArray()(one row) orcountAllResults()
Writing
insert($data), insertBatch($rows), where(...)->update($data), where(...)->delete(). $db->insertID() gives the new id.
Raw queries safely
$db->query('SELECT * FROM users WHERE email = ?', [$email]) — always use bindings (?). The Query Builder escapes values for you, protecting against SQL injection.
Example
Example — Published posts with author names
PHP
<?php
$db = db_connect();
$posts = $db->table('posts')
->select('posts.id, posts.title, users.name AS author')
->join('users', 'users.id = posts.user_id')
->where('posts.status', 'published')
->like('posts.title', 'php')
->orderBy('posts.id', 'DESC')
->limit(5)
->get()
->getResultArray();
foreach ($posts as $post) {
echo $post['title'] . ' by ' . $post['author'] . PHP_EOL;
}
// Insert and get the new id
$db->table('posts')->insert(['user_id' => 1, 'title' => 'PHP Tips', 'status' => 'draft']);
echo $db->insertID();
Prints up to 5 published posts with "php" in the title, e.g. "PHP Tips by Asha", newest first. insertID() prints the id of the row just inserted.