agyanadda@gmail.com

CodeIgniter 4 Database and Query Builder

Database and Models 1 min read Updated Dec 3, 2026 Topic 10 of 30

Connect to the database

Set these in .env:

  • database.default.hostname = localhost
  • database.default.database = ci4_blog
  • database.default.username = root
  • database.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) or countAllResults()

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.

Test Yourself With Exercises

Exercise 1 Multiple Choice

Which method returns all result rows as arrays?

Exercise 2 True / False

Query Builder escapes values automatically to help prevent SQL injection.

Exercise 3 Fill in the Blank

Get the id of the last inserted row with $db->___()

Frequently Asked Questions

Call $db->getLastQuery() after running a query, or use ->getCompiledSelect() instead of ->get() to see the SQL without running it. The Debug Toolbar in development mode also lists every query.