Documentation

Model extends CI_Model
in package

AbstractYes

Extended Model class with query builder integration.

Base model class that wraps CodeIgniter's query builder methods and provides automatic table name resolution via the TABLE constant.

Usage:

class UserModel extends \X\Model\Model {
  const TABLE = 'users';

  public function findActive() {
    return $this->where('active', 1)->get_all();
  }
}

Table of Contents

Constants

TABLE  = ''
Table name.

Properties

$library  : string|array<string|int, string>
Auto-loading library name.
$model  : string|array<string|int, string>
Auto-loading model name.

Methods

__construct()  : mixed
Initialize Model.
cache_delete()  : void
Delete the cache files associated with a particular URI.
cache_delete_all()  : void
Delete All cache files.
cache_off()  : void
Disable Query Caching.
cache_on()  : void
Enable Query Caching.
count_all()  : int
Returns the total number of rows in a table, or 0 if no table was provided.
count_all_results()  : int
"Count All Results" query.
count_by_id()  : int
Get counts matching ID.
db()  : CI_DB
Get database object.
dbprefix()  : string
DB Prefix. Prepends a database prefix if one exists in configuration
delete()  : CI_DB_query_builder
Delete.
distinct()  : Model
Sets a flag which tells the query string compiler to add DISTINCT.
empty_table()  : bool
Empty Table.
error()  : array{code: string|null, message: string|null}
Last error.
escape()  : mixed
Escapes input data based on type, including boolean and NULLs.
escape_like_str()  : mixed
Escape LIKE strings.
escape_str()  : string
Escapes string values.
exists_by_id()  : bool
Check if the ID exists.
field_data()  : array<string|int, mixed>
Gets a list containing field data about a table.
field_exists()  : bool
Determine if a particular field exists.
flush_cache()  : Model
Flush Cache.
from()  : Model
Generates the FROM portion of the query
get()  : CI_DB_result
Compiles and runs SELECT statement based on the already called Query Builder methods.
get_all()  : array<string|int, mixed>
Query result. "array" version.
get_by_id()  : array<string|int, mixed>
Find records matching the ID.
get_compiled_delete()  : string
Compiles a DELETE statement and returns it as a string.
get_compiled_insert()  : string
Get INSERT query string.
get_compiled_select()  : string
Compiles a SELECT statement and returns it as a string.
get_compiled_update()  : string
Get UPDATE query string
get_where()  : CI_DB_result
Allows the where clause, limit and offset to be added directly.
group_by()  : Model
GROUP BY.
group_end()  : Model
Ends a query group.
group_start()  : Model
Starts a query group.
having()  : Model
HAVING. Separates multiple calls with 'AND'.
insert()  : int
Insert.
insert_batch()  : array<string|int, int>
Insert_Batch.
insert_id()  : int
Insert ID.
insert_on_duplicate_update()  : int
Insert_On_Duplicate_Key_Update.
insert_on_duplicate_update_batch()  : int
Insert_On_Duplicate_Key_Update_Batch.
is_connect()  : bool
DB connection check.
join()  : Model
Generates the JOIN portion of the query
last_query()  : string
Returns the last query that was executed.
like()  : Model
Generates a %LIKE% portion of the query. Separates multiple calls with 'AND'.
limit()  : Model
LIMIT.
list_fields()  : array<string|int, mixed>
Gets a list of the field names in a table.
list_tables()  : array<string|int, mixed>
Gets a list of the tables in the current database.
load_rdriver()  : string
Load the result drivers.
not_group_start()  : Model
Starts a query group, but NOTs the group.
not_like()  : Model
Generates a NOT LIKE portion of the query. Separates multiple calls with 'AND'.
offset()  : Model
Sets the OFFSET value.
or_group_start()  : Model
Starts a query group, but ORs the group.
or_having()  : Model
OR HAVING. Separates multiple calls with 'OR'.
or_like()  : Model
Generates a %LIKE% portion of the query. Separates multiple calls with 'OR'.
or_not_group_start()  : Model
Starts a query group, but OR NOTs the group.
or_not_like()  : Model
Generates a NOT LIKE portion of the query. Separates multiple calls with 'OR'.
or_where()  : CI_DB_query_builder
Generates the WHERE portion of the query. Separates multiple calls with 'OR'.
or_where_in()  : Model
Generates a WHERE field IN('item', 'item') SQL query, joined with 'OR' if appropriate.
or_where_not_in()  : Model
Generates a WHERE field NOT IN('item', 'item') SQL query, joined with 'OR' if appropriate.
order_by()  : Model
ORDER BY.
primary()  : string
Retrieves the primary key of a table.
query()  : mixed
Execute the query.
replace()  : bool
Replace.
reset_query()  : Model
Reset Query Builder values.
select()  : Model
Generates the SELECT portion of the query.
select_avg()  : Model
Generates a SELECT AVG(field) portion of a query.
select_max()  : Model
Generates a SELECT MAX(field) portion of a query.
select_min()  : Model
Generates a SELECT MIN(field) portion of a query.
select_sum()  : Model
Generates a SELECT SUM(field) portion of a query.
set()  : Model
Allows key/value pairs to be set for inserting or updating
set_dbprefix()  : string
Set's the DB Prefix to something new without needing to reconnect
set_foreign_key_checks()  : bool
Set foreign key check.
set_insert_batch()  : Model
The "set_insert_batch" function. Allows key/value pairs to be set for batch inserts.
set_update_batch()  : Model
The "set_update_batch" function. Allows key/value pairs to be set for batch updating
start_cache()  : Model
Starts QB caching.
stop_cache()  : Model
Stops QB caching
table_exists()  : bool
Determine if a particular table exists.
trans_begin()  : bool
Begin Transaction.
trans_commit()  : bool
Commit Transaction.
trans_complete()  : bool
Complete Transaction.
trans_rollback()  : bool
Rollback Transaction.
trans_start()  : bool
Start Transaction.
trans_status()  : bool
Lets you retrieve the transaction flag to determine if it has failed.
truncate()  : bool
Truncate.
update()  : void
Update.
update_batch()  : int
Update_Batch.
where()  : Model
Generates the WHERE portion of the query. Separates multiple calls with 'AND'.
where_in()  : Model
Generates a WHERE field IN('item', 'item') SQL query, joined with 'AND' if appropriate.
where_not_in()  : Model
Generates a WHERE field NOT IN('item', 'item') SQL query, joined with 'AND' if appropriate.

Constants

TABLE

Table name.

public string TABLE = ''

Properties

$library

Auto-loading library name.

protected string|array<string|int, string> $library

$model

Auto-loading model name.

protected string|array<string|int, string> $model

Methods

__construct()

Initialize Model.

public __construct() : mixed

cache_delete()

Delete the cache files associated with a particular URI.

public cache_delete([string $segmentOne = '' ][, string $segmentTwo = '' ]) : void
Parameters
$segmentOne : string = ''

First URI segment.

$segmentTwo : string = ''

Second URI segment.

Tags
example

Delete specific cache

// Delete cache for /users/list page
$this->UserModel->cache_delete('users', 'list');

cache_delete_all()

Delete All cache files.

public cache_delete_all() : void
Tags
example

Clear all query cache

$this->UserModel->cache_delete_all();

cache_off()

Disable Query Caching.

public cache_off() : void

cache_on()

Enable Query Caching.

public cache_on() : void
Tags
example

Cache query results

// config/database.php: $db['default']['cachedir'] = APPPATH . 'cache';
$this->UserModel->cache_on();
$users = $this->UserModel->where('status', 'active')->get_all(); // Cached
$this->UserModel->cache_off();

count_all()

Returns the total number of rows in a table, or 0 if no table was provided.

public count_all([string $table = '' ]) : int
Parameters
$table : string = ''

(optional) Table name.

Return values
int

Row count for the specified table.

count_all_results()

"Count All Results" query.

public count_all_results([string $table = '' ][, bool $reset = true ]) : int

Generates a platform-specific query string that counts all records returned by an Query Builder query.

Parameters
$table : string = ''

(optional) Table name.

$reset : bool = true

Whether to reset values for SELECTs.

Tags
example

Count filtered records

$activeCount = $this->UserModel
  ->where('status', 'active')
  ->count_all_results();
// SELECT COUNT(*) FROM users WHERE status = 'active'
example

Count for pagination

$totalCount = $this->UserModel
  ->like('name', $searchKeyword)
  ->count_all_results('', false); // false = don't reset query

$users = $this->UserModel
  ->limit($perPage, $offset)
  ->get_all();
Return values
int

count_by_id()

Get counts matching ID.

public count_by_id(int $id) : int
Parameters
$id : int

ID.

Tags
example

Count specific user

$count = $this->UserModel->count_by_id(1);
// Returns 1 if user exists, 0 if not
Return values
int

Search result count.

db()

Get database object.

public static db([string $config = 'default' ]) : CI_DB
Parameters
$config : string = 'default'

Connection group name. Default is "default".

Tags
example

Execute raw query with parameter binding

$result = UserModel::db()->query(
  'SELECT * FROM users WHERE status = ? AND created_at > ?',
  ['active', '2024-01-01']
);
foreach ($result->result_array() as $row) {
  echo $row['name'];
}
example

Use different database connection (config/database.php)

// Read from replica database
$users = UserModel::db('replica')
  ->select('*')
  ->from('users')
  ->get()
  ->result_array();
Return values
CI_DB

CI_DB instance.

dbprefix()

DB Prefix. Prepends a database prefix if one exists in configuration

public dbprefix([string $table = '' ]) : string
Parameters
$table : string = ''

(optional) The table name to prefix.

Return values
string

The prefixed table name.

delete()

Delete.

public delete([string $table = '' ][, string $where = '' ][, int $limit = null ][, bool $reset = true ]) : CI_DB_query_builder
Parameters
$table : string = ''

(optional) The table(s) to delete from; string or array.

$where : string = ''

(optional) The WHERE clause.

$limit : int = null

The (optional) LIMIT clause.

$reset : bool = true

(optional) TRUE to reset the query "write" clause.

Tags
example

Delete by ID

$this->UserModel->delete('', ['id' => 1]);
example

Delete with where()

$this->UserModel->where('id', 1)->delete();
example

Delete with multiple conditions

$this->UserModel
  ->where('status', 'inactive')
  ->where('last_login <', '2023-01-01')
  ->delete();
Return values
CI_DB_query_builder

instance (method chaining) or FALSE on failure.

distinct()

Sets a flag which tells the query string compiler to add DISTINCT.

public distinct([bool $val = true ]) : Model
Parameters
$val : bool = true

Desired value of the "distinct" flag.

Tags
example

Get unique values

$categories = $this->ProductModel
  ->distinct()
  ->select('category')
  ->get_all();
// SELECT DISTINCT category FROM products
Return values
Model

empty_table()

Empty Table.

public empty_table([string $table = '' ]) : bool
Parameters
$table : string = ''

(optional) Table name.

Tags
example

Delete all records from table

$this->LogModel->empty_table();
// DELETE FROM logs
Return values
bool

true on success, false on failure.

error()

Last error.

public error() : array{code: string|null, message: string|null}
Tags
example

Check for database errors

$this->UserModel->insert('', $data);
$error = $this->UserModel->error();
if ($error['code']) {
  \X\Util\Logger::error("DB Error: {$error['message']}");
}
Return values
array{code: string|null, message: string|null}

Error data.

escape()

Escapes input data based on type, including boolean and NULLs.

public escape(mixed $str) : mixed
Parameters
$str : mixed

The value to escape, or an array of multiple ones.

Tags
example

Escape user input for raw queries

$name = $this->UserModel->escape($this->input->post('name'));
$this->UserModel->query("SELECT * FROM users WHERE name = {$name}");
Return values
mixed

The escaped value(s).

escape_like_str()

Escape LIKE strings.

public escape_like_str(string|array<string|int, string> $str) : mixed
Parameters
$str : string|array<string|int, string>

A string value or array of multiple ones.

Return values
mixed

The escaped string(s).

escape_str()

Escapes string values.

public escape_str(string|array<string|int, string> $str[, bool $like = false ]) : string
Parameters
$str : string|array<string|int, string>

A string value or array of multiple ones.

$like : bool = false

(optional) Whether or not the string will be used in a LIKE condition.

Return values
string

The escaped string(s).

exists_by_id()

Check if the ID exists.

public exists_by_id(int $id) : bool
Parameters
$id : int

ID.

Tags
example

Check existence before delete

public function delete($id) {
  if (!$this->UserModel->exists_by_id($id)) {
    $this->error('User not found', 404);
    return;
  }
  $this->UserModel->delete('', ['id' => $id]);
  $this->set('success', true)->json();
}
Return values
bool

Whether the ID exists.

field_data()

Gets a list containing field data about a table.

public field_data([string $table = null ]) : array<string|int, mixed>
Parameters
$table : string = null

(optional) The table name.

Return values
array<string|int, mixed>

Array of field data items or FALSE on failure.

field_exists()

Determine if a particular field exists.

public field_exists(string $field[, string $table = null ]) : bool
Parameters
$field : string

The field name.

$table : string = null

(optional) The table name.

Return values
bool

TRUE if that field exists in that table, FALSE if not

flush_cache()

Flush Cache.

public flush_cache() : Model

Empties the QB cache.

Return values
Model

from()

Generates the FROM portion of the query

public from(mixed $from) : Model
Parameters
$from : mixed

Table name(s); string or array.

Return values
Model

get()

Compiles and runs SELECT statement based on the already called Query Builder methods.

public get([string $table = '' ][, string $limit = null ][, string $offset = null ]) : CI_DB_result
Parameters
$table : string = ''

(optional) The table to query.

$limit : string = null

(optional) The LIMIT clause.

$offset : string = null

(optional) The OFFSET clause.

Return values
CI_DB_result

get_all()

Query result. "array" version.

public get_all() : array<string|int, mixed>
Tags
example

Get all records

$users = $this->UserModel->get_all();
// [['id' => 1, 'name' => 'John'], ['id' => 2, 'name' => 'Jane']]
example

Get filtered records

$activeUsers = $this->UserModel->where('status', 'active')->get_all();
example

Get with conditions and ordering

$recentUsers = $this->UserModel
  ->where('created_at >', '2024-01-01')
  ->order_by('created_at', 'DESC')
  ->limit(10)
  ->get_all();
Return values
array<string|int, mixed>

Search result data.

get_by_id()

Find records matching the ID.

public get_by_id(int $id) : array<string|int, mixed>
Parameters
$id : int

ID.

Tags
example

Get single record by ID

$user = $this->UserModel->get_by_id(1);
// ['id' => 1, 'name' => 'John', 'email' => 'john@example.com']
example

Use in controller

public function show($id) {
  $user = $this->UserModel->get_by_id($id);
  if (!$user) {
    $this->error('User not found', 404);
    return;
  }
  $this->set('user', $user)->json();
}
Return values
array<string|int, mixed>

Search result data.

get_compiled_delete()

Compiles a DELETE statement and returns it as a string.

public get_compiled_delete([string $table = '' ][, bool $reset = true ]) : string
Parameters
$table : string = ''

(optional) Table name.

$reset : bool = true

(optional) Whether to reset the current QB values or not.

Return values
string

The compiled SQL statement as a string.

get_compiled_insert()

Get INSERT query string.

public get_compiled_insert([string $table = '' ][, bool $reset = true ]) : string
Parameters
$table : string = ''

(optional) Table name.

$reset : bool = true

(optional) Whether to reset the current QB values or not.

Return values
string

Compiles an INSERT statement and returns it as a string.

get_compiled_select()

Compiles a SELECT statement and returns it as a string.

public get_compiled_select([string $table = '' ][, bool $reset = true ]) : string
Parameters
$table : string = ''

(optional) Table name.

$reset : bool = true

(optional) Whether to reset the current QB values or not.

Return values
string

The compiled SQL statement as a string.

get_compiled_update()

Get UPDATE query string

public get_compiled_update([string $table = '' ][, bool $reset = true ]) : string
Parameters
$table : string = ''

(optional) Table name.

$reset : bool = true

(optional) Whether to reset the current QB values or not.

Return values
string

The compiled SQL statement as a string.

get_where()

Allows the where clause, limit and offset to be added directly.

public get_where([string $table = '' ][, string $where = null ][, int $limit = null ][, int $offset = null ]) : CI_DB_result
Parameters
$table : string = ''

(optional) The table(s) to fetch data from; string or array.

$where : string = null

(optional) The WHERE clause.

$limit : int = null

(optional) The LIMIT clause.

$offset : int = null

(optional) The OFFSET clause.

Return values
CI_DB_result

group_by()

GROUP BY.

public group_by(string $by[, bool $escape = null ]) : Model
Parameters
$by : string

Field(s) to group by; string or array.

$escape : bool = null

(optional) Whether to escape values and identifiers.

Tags
example

Group by single column

$stats = $this->OrderModel
  ->select('status, COUNT(*) as count')
  ->group_by('status')
  ->get_all();
// [['status' => 'pending', 'count' => 5], ['status' => 'completed', 'count' => 20]]
example

Group by multiple columns

$stats = $this->OrderModel
  ->select('YEAR(created_at) as year, MONTH(created_at) as month, SUM(total) as total')
  ->group_by(['YEAR(created_at)', 'MONTH(created_at)'])
  ->get_all();
Return values
Model

group_end()

Ends a query group.

public group_end() : Model
Return values
Model

group_start()

Starts a query group.

public group_start([string $not = '' ][, string $type = 'AND ' ]) : Model
Parameters
$not : string = ''

(Internal use only).

$type : string = 'AND '

(Internal use only).

Tags
example

Complex WHERE conditions with grouping

$users = $this->UserModel
  ->where('status', 'active')
  ->group_start()
    ->where('role', 'admin')
    ->or_where('role', 'manager')
  ->group_end()
  ->get_all();
// SELECT * FROM users WHERE status = 'active' AND (role = 'admin' OR role = 'manager')
Return values
Model

having()

HAVING. Separates multiple calls with 'AND'.

public having(string $key[, string $value = null ][, bool $escape = null ]) : Model
Parameters
$key : string

Identifier (string) or associative array of field/value pairs.

$value : string = null

Value sought if $key is an identifier.

$escape : bool = null

(optional) Whether to escape values and identifiers.

Tags
example

Filter grouped results

$topCustomers = $this->OrderModel
  ->select('user_id, SUM(total) as total_spent')
  ->group_by('user_id')
  ->having('total_spent >', 10000)
  ->get_all();
// SELECT user_id, SUM(total) as total_spent FROM orders
// GROUP BY user_id HAVING total_spent > 10000
Return values
Model

insert()

Insert.

public insert([string $table = '' ][, array<string|int, mixed>|object $set = null ][, bool $escape = null ]) : int
Parameters
$table : string = ''

(optional) Table name.

$set : array<string|int, mixed>|object = null

(optional) An associative array of field/value pairs.

$escape : bool = null

(optional) Whether to escape values and identifiers.

Tags
example

Insert with set() method

$this->UserModel
  ->set('name', 'John')
  ->set('email', 'john@example.com')
  ->insert();
example

Insert with array

$id = $this->UserModel->insert('', [
  'name' => 'John',
  'email' => 'john@example.com',
  'created_at' => date('Y-m-d H:i:s')
]);
echo "New user ID: $id";
Return values
int

Insert ID.

insert_batch()

Insert_Batch.

public insert_batch(string $table[, array<string|int, mixed>|object $set = null ][, bool $escape = null ][, int $batchSize = 100 ]) : array<string|int, int>
Parameters
$table : string

Table name.

$set : array<string|int, mixed>|object = null

(optional) Data to insert.

$escape : bool = null

(optional) Whether to escape values and identifiers.

$batchSize : int = 100

(optional) Count of rows to insert at once. Default is 100.

Tags
example

Insert multiple records at once

$this->UserModel->insert_batch('users', [
  ['name' => 'John', 'email' => 'john@example.com'],
  ['name' => 'Jane', 'email' => 'jane@example.com'],
  ['name' => 'Bob', 'email' => 'bob@example.com']
]);
Return values
array<string|int, int>

Insert ID.

insert_id()

Insert ID.

public insert_id() : int
Return values
int

Insert ID.

insert_on_duplicate_update()

Insert_On_Duplicate_Key_Update.

public insert_on_duplicate_update([string $table = '' ][, array<string|int, mixed>|object $set = null ][, bool $escape = null ]) : int
Parameters
$table : string = ''

(optional) Table name.

$set : array<string|int, mixed>|object = null

(optional) an associative array of insert values.

$escape : bool = null

(optional) Whether to escape values and identifiers.

Tags
example

Insert or update user by email

$this->UserModel
  ->set([
    'email' => 'john@example.com',
    'name' => 'John',
    'updated_at' => date('Y-m-d H:i:s')
  ])
  ->insert_on_duplicate_update();
example

Using chained set() calls

$this->UserModel
  ->set('email', 'john@example.com')
  ->set('name', 'John')
  ->set('login_count', 1)
  ->insert_on_duplicate_update();
Return values
int

Insert ID.

insert_on_duplicate_update_batch()

Insert_On_Duplicate_Key_Update_Batch.

public insert_on_duplicate_update_batch([string $table = '' ][, array<string|int, mixed>|object $set = null ][, bool $escape = null ][, int $batchSize = 100 ]) : int
Parameters
$table : string = ''

(optional) Table name.

$set : array<string|int, mixed>|object = null

(optional) an associative array of insert values.

$escape : bool = null

(optional) Whether to escape values and identifiers.

$batchSize : int = 100

(optional) Count of rows to insert at once. Default is 100.

Tags
example

Batch upsert users

$this->UserModel
  ->set_insert_batch([
    ['email' => 'john@example.com', 'name' => 'John', 'role' => 'user'],
    ['email' => 'jane@example.com', 'name' => 'Jane', 'role' => 'admin']
  ])
  ->insert_on_duplicate_update_batch();
Return values
int

Number of rows inserted or false on failure.

is_connect()

DB connection check.

public static is_connect([string $config = 'default' ]) : bool
Parameters
$config : string = 'default'

Connection group name. Default is "default".

Tags
example

Check database availability

if (!UserModel::is_connect()) {
  $this->error('Database connection failed', 503);
  return;
}
Return values
bool

Whether you could connect to DB or not.

join()

Generates the JOIN portion of the query

public join(string $table, string $cond[, string $type = '' ][, bool $escape = null ]) : Model
Parameters
$table : string

Table name.

$cond : string

The JOIN ON condition.

$type : string = ''

(optional) The JOIN type.

$escape : bool = null

(optional) Whether to escape values and identifiers.

Tags
example

Inner join

$users = $this->UserModel
  ->select('users.*, roles.name as role_name')
  ->join('roles', 'roles.id = users.role_id')
  ->get_all();
example

Left join

$users = $this->UserModel
  ->select('users.*, profiles.avatar')
  ->join('profiles', 'profiles.user_id = users.id', 'left')
  ->get_all();
Return values
Model

last_query()

Returns the last query that was executed.

public last_query() : string
Tags
example

Debug query

$users = $this->UserModel->where('status', 'active')->get_all();
\X\Util\Logger::debug($this->UserModel->last_query());
// SELECT * FROM users WHERE status = 'active'
Return values
string

The last query executed.

like()

Generates a %LIKE% portion of the query. Separates multiple calls with 'AND'.

public like(mixed $field[, string $match = '' ][, string $side = 'both' ][, bool $escape = null ]) : Model
Parameters
$field : mixed

Field name.

$match : string = ''

(optional) Text portion to match.

$side : string = 'both'

(optional) Which side of the expression to put the '%' wildcard on.

$escape : bool = null

(optional) Whether to escape values and identifiers.

Tags
example

Search with wildcard on both sides (default)

$users = $this->UserModel->like('name', 'john')->get_all();
// SELECT * FROM users WHERE name LIKE '%john%'
example

Search with wildcard on right side only (starts with)

$users = $this->UserModel->like('email', 'admin', 'after')->get_all();
// SELECT * FROM users WHERE email LIKE 'admin%'
example

Search with wildcard on left side only (ends with)

$users = $this->UserModel->like('email', '@gmail.com', 'before')->get_all();
// SELECT * FROM users WHERE email LIKE '%@gmail.com'
Return values
Model

limit()

LIMIT.

public limit(int $value[, int $offset = 0 ]) : Model
Parameters
$value : int

Number of rows to limit the results to.

$offset : int = 0

Number of rows to skip.

Tags
example

Limit results

$users = $this->UserModel->limit(10)->get_all();
// SELECT * FROM users LIMIT 10
example

Pagination

$page = 2;
$perPage = 10;
$users = $this->UserModel
  ->limit($perPage, ($page - 1) * $perPage)
  ->get_all();
// SELECT * FROM users LIMIT 10 OFFSET 10
Return values
Model

list_fields()

Gets a list of the field names in a table.

public list_fields([string $table = null ]) : array<string|int, mixed>
Parameters
$table : string = null

(optional) The table name.

Return values
array<string|int, mixed>

Array of field names or FALSE on failure.

list_tables()

Gets a list of the tables in the current database.

public list_tables([string $constrainByPrefix = false ]) : array<string|int, mixed>
Parameters
$constrainByPrefix : string = false

(optional) TRUE to match table names by the configured dbprefix.

Return values
array<string|int, mixed>

Array of table names or FALSE on failure.

load_rdriver()

Load the result drivers.

public load_rdriver() : string
Return values
string

the name of the result class.

not_group_start()

Starts a query group, but NOTs the group.

public not_group_start() : Model
Return values
Model

not_like()

Generates a NOT LIKE portion of the query. Separates multiple calls with 'AND'.

public not_like(mixed $field[, string $match = '' ][, string $side = 'both' ][, bool $escape = null ]) : Model
Parameters
$field : mixed

Field name.

$match : string = ''

(optional) Text portion to match.

$side : string = 'both'

(optional) Which side of the expression to put the ‘%’ wildcard on.

$escape : bool = null

(optional) Whether to escape values and identifiers.

Return values
Model

offset()

Sets the OFFSET value.

public offset(int $offset) : Model
Parameters
$offset : int

Number of rows to skip.

Return values
Model

or_group_start()

Starts a query group, but ORs the group.

public or_group_start() : Model
Return values
Model

or_having()

OR HAVING. Separates multiple calls with 'OR'.

public or_having(string $key[, string $value = null ][, bool $escape = null ]) : Model
Parameters
$key : string

Identifier (string) or associative array of field/value pairs.

$value : string = null

Value sought if $key is an identifier.

$escape : bool = null

(optional) Whether to escape values and identifiers.

Return values
Model

or_like()

Generates a %LIKE% portion of the query. Separates multiple calls with 'OR'.

public or_like(mixed $field[, string $match = '' ][, string $side = 'both' ][, bool $escape = null ]) : Model
Parameters
$field : mixed

Field name.

$match : string = ''

(optional) Text portion to match.

$side : string = 'both'

(optional) Which side of the expression to put the ‘%’ wildcard on.

$escape : bool = null

(optional) Whether to escape values and identifiers.

Return values
Model

or_not_group_start()

Starts a query group, but OR NOTs the group.

public or_not_group_start() : Model
Return values
Model

or_not_like()

Generates a NOT LIKE portion of the query. Separates multiple calls with 'OR'.

public or_not_like(mixed $field[, string $match = '' ][, string $side = 'both' ][, bool $escape = null ]) : Model
Parameters
$field : mixed

Field name.

$match : string = ''

(optional) Text portion to match.

$side : string = 'both'

(optional) Which side of the expression to put the ‘%’ wildcard on.

$escape : bool = null

(optional) Whether to escape values and identifiers.

Return values
Model

or_where()

Generates the WHERE portion of the query. Separates multiple calls with 'OR'.

public or_where(string $key[, mixed $value = null ][, bool $escape = null ]) : CI_DB_query_builder
Parameters
$key : string

Name of field to compare, or associative array.

$value : mixed = null

(optional) If a single key, compared to this value.

$escape : bool = null

(optional) Whether to escape values and identifiers.

Return values
CI_DB_query_builder

or_where_in()

Generates a WHERE field IN('item', 'item') SQL query, joined with 'OR' if appropriate.

public or_where_in([string $key = null ][, array<string|int, mixed> $values = null ][, bool $escape = null ]) : Model
Parameters
$key : string = null

(optional) The field to search.

$values : array<string|int, mixed> = null

(optional) The values searched on.

$escape : bool = null

(optional) Whether to escape values and identifiers.

Return values
Model

or_where_not_in()

Generates a WHERE field NOT IN('item', 'item') SQL query, joined with 'OR' if appropriate.

public or_where_not_in([string $key = null ][, array<string|int, mixed> $values = null ][, bool $escape = null ]) : Model
Parameters
$key : string = null

(optional) The field to search.

$values : array<string|int, mixed> = null

(optional) The values searched on.

$escape : bool = null

(optional) Whether to escape values and identifiers.

Return values
Model

order_by()

ORDER BY.

public order_by(string $orderby[, string $direction = '' ][, bool $escape = null ]) : Model
Parameters
$orderby : string

Field to order by.

$direction : string = ''

The order requested - ASC, DESC or random.

$escape : bool = null

(optional) Whether to escape values and identifiers.

Tags
example

Order by single column

$users = $this->UserModel->order_by('created_at', 'DESC')->get_all();
example

Multiple order by

$users = $this->UserModel
  ->order_by('role', 'ASC')
  ->order_by('name', 'ASC')
  ->get_all();
example

Random order

$users = $this->UserModel->order_by('id', 'RANDOM')->limit(5)->get_all();
Return values
Model

primary()

Retrieves the primary key of a table.

public primary([string $table = null ]) : string
Parameters
$table : string = null

(optional) Table name.

Return values
string

The primary key name, FALSE if none.

query()

Execute the query.

public query(string $sql[, array<string|int, mixed>|false $binds = false ][, bool $returnObject = null ]) : mixed
Parameters
$sql : string

The SQL statement to execute.

$binds : array<string|int, mixed>|false = false

(optional) An array of binding data.

$returnObject : bool = null

(optional) Whether to return a result object or not.

Tags
example

Execute SELECT query

$result = $this->UserModel->query(
  'SELECT * FROM users WHERE role = ? ORDER BY name',
  ['admin']
);
$users = $result->result_array();
example

Execute stored procedure

$result = $this->UserModel->query('CALL get_user_stats(?)', [$userId]);
Return values
mixed

true for successful "write-type" queries, CI_DB_result instance (method chaining) on "query" success, false on failure.

replace()

Replace.

public replace([string $table = '' ][, array<string|int, mixed>|null $set = null ]) : bool
Parameters
$table : string = ''

(optional) Table name.

$set : array<string|int, mixed>|null = null

(optional) An associative array of field/value pairs.

Return values
bool

true on success, false on failure.

reset_query()

Reset Query Builder values.

public reset_query() : Model

Publicly-visible method to reset the QB values.

Return values
Model

select()

Generates the SELECT portion of the query.

public select([string $select = '*' ][, bool $escape = null ]) : Model
Parameters
$select : string = '*'

(optional) The SELECT portion of a query.

$escape : bool = null

(optional) Whether to escape values and identifiers.

Tags
example

Select specific columns

$users = $this->UserModel->select('id, name, email')->get_all();
example

Select with alias

$users = $this->UserModel
  ->select('id, CONCAT(first_name, " ", last_name) as full_name')
  ->get_all();
Return values
Model

select_avg()

Generates a SELECT AVG(field) portion of a query.

public select_avg([string $select = '' ][, string $alias = '' ]) : Model
Parameters
$select : string = ''

(optional) Field to compute the average of.

$alias : string = ''

(optional) Alias for the resulting value name.

Tags
example

Get average value

$result = $this->OrderModel->select_avg('total', 'avg_order')->get()->row_array();
echo $result['avg_order']; // 5420.50
Return values
Model

select_max()

Generates a SELECT MAX(field) portion of a query.

public select_max([string $select = '' ][, string $alias = '' ]) : Model
Parameters
$select : string = ''

(optional) Field to compute the maximum of.

$alias : string = ''

(optional) Alias for the resulting value name.

Tags
example

Get maximum value

$result = $this->OrderModel->select_max('total', 'max_total')->get()->row_array();
echo $result['max_total']; // 99800
Return values
Model

select_min()

Generates a SELECT MIN(field) portion of a query.

public select_min([string $select = '' ][, string $alias = '' ]) : Model
Parameters
$select : string = ''

(optional) Field to compute the minimum of.

$alias : string = ''

(optional) Alias for the resulting value name.

Tags
example

Get minimum value

$result = $this->ProductModel->select_min('price', 'min_price')->get()->row_array();
echo $result['min_price']; // 100
Return values
Model

select_sum()

Generates a SELECT SUM(field) portion of a query.

public select_sum([string $select = '' ][, string $alias = '' ]) : Model
Parameters
$select : string = ''

(optional) Field to compute the sum of.

$alias : string = ''

(optional) Alias for the resulting value name.

Tags
example

Get sum of values

$result = $this->OrderModel
  ->select_sum('total', 'total_sales')
  ->where('created_at >=', '2024-01-01')
  ->get()
  ->row_array();
echo $result['total_sales']; // 1250000
Return values
Model

set()

Allows key/value pairs to be set for inserting or updating

public set(mixed $key[, string $value = '' ][, bool $escape = null ]) : Model
Parameters
$key : mixed

Field name, or an array of field/value pairs.

$value : string = ''

(optional) Field value, if $key is a single field.

$escape : bool = null

(optional) Whether to escape values and identifiers.

Return values
Model

set_dbprefix()

Set's the DB Prefix to something new without needing to reconnect

public set_dbprefix([string $prefix = '' ]) : string
Parameters
$prefix : string = ''

The new prefix to use.

Return values
string

The DB prefix in use.

set_foreign_key_checks()

Set foreign key check.

public set_foreign_key_checks(bool $enabled) : bool
Parameters
$enabled : bool

Value of foreign_key_checks.

Return values
bool

TRUE on success, FALSE on failure.

set_insert_batch()

The "set_insert_batch" function. Allows key/value pairs to be set for batch inserts.

public set_insert_batch(mixed $key[, string $value = '' ][, bool $escape = null ]) : Model
Parameters
$key : mixed

Field name or an array of field/value pairs.

$value : string = ''

(optional) Field value, if $key is a single field.

$escape : bool = null

(optional) Whether to escape values and identifiers.

Return values
Model

set_update_batch()

The "set_update_batch" function. Allows key/value pairs to be set for batch updating

public set_update_batch(array<string|int, mixed> $key[, string $value = '' ][, bool $escape = null ]) : Model
Parameters
$key : array<string|int, mixed>

Field name or an array of field/value pairs.

$value : string = ''

(optional) Field value, if $key is a single field.

$escape : bool = null

(optional) Whether to escape values and identifiers.

Return values
Model

start_cache()

Starts QB caching.

public start_cache() : Model
Return values
Model

stop_cache()

Stops QB caching

public stop_cache() : Model
Return values
Model

table_exists()

Determine if a particular table exists.

public table_exists([string $table = null ]) : bool
Parameters
$table : string = null

(optional) The table name.

Return values
bool

TRUE if that table exists, FALSE if not.

trans_begin()

Begin Transaction.

public trans_begin([bool $testMode = false ]) : bool
Parameters
$testMode : bool = false

(optional) Test mode flag.

Tags
example

Manual transaction control

$this->UserModel->trans_begin();

try {
  $this->UserModel->insert('', ['name' => 'John']);
  $this->OrderModel->insert('', ['user_id' => 1]);
  $this->UserModel->trans_commit();
} catch (\Exception $e) {
  $this->UserModel->trans_rollback();
  throw $e;
}
Return values
bool

TRUE on success, FALSE on failure.

trans_commit()

Commit Transaction.

public trans_commit() : bool
Return values
bool

TRUE on success, FALSE on failure.

trans_complete()

Complete Transaction.

public trans_complete() : bool
Return values
bool

TRUE on success, FALSE on failure.

trans_rollback()

Rollback Transaction.

public trans_rollback() : bool
Return values
bool

TRUE on success, FALSE on failure.

trans_start()

Start Transaction.

public trans_start([bool $testMode = false ]) : bool
Parameters
$testMode : bool = false

(optional) Test mode flag.

Tags
example

Basic transaction

$this->UserModel->trans_start();
$this->UserModel->insert('', ['name' => 'John']);
$this->OrderModel->insert('', ['user_id' => 1, 'total' => 100]);
$this->UserModel->trans_complete();

if ($this->UserModel->trans_status() === false) {
  // Transaction failed
}
Return values
bool

TRUE on success, FALSE on failure.

trans_status()

Lets you retrieve the transaction flag to determine if it has failed.

public trans_status() : bool
Return values
bool

TRUE if the transaction succeeded, FALSE if it failed.

truncate()

Truncate.

public truncate([string $table = '' ]) : bool
Parameters
$table : string = ''

(optional) Table name.

Tags
example

Reset table and auto-increment

$this->TempDataModel->truncate();
// TRUNCATE TABLE temp_data
Return values
bool

true on success, false on failure.

update()

Update.

public update([string $table = '' ][, array<string|int, mixed>|object $set = null ][, string|array<string|int, mixed> $where = null ][, int $limit = null ]) : void
Parameters
$table : string = ''

(optional) Table name.

$set : array<string|int, mixed>|object = null

(optional) An associative array of field/value pairs.

$where : string|array<string|int, mixed> = null

(optional) The WHERE clause.

$limit : int = null

(optional) The LIMIT clause.

Tags
example

Update with set() and where()

$this->UserModel
  ->set('name', 'John Doe')
  ->set('updated_at', date('Y-m-d H:i:s'))
  ->where('id', 1)
  ->update();
example

Update with array

$this->UserModel->update('', [
  'status' => 'inactive',
  'updated_at' => date('Y-m-d H:i:s')
], ['id' => 1]);
example

Batch update with condition

$this->UserModel
  ->set('status', 'expired')
  ->where('subscription_end <', date('Y-m-d'))
  ->update();

update_batch()

Update_Batch.

public update_batch(string $table[, array<string|int, mixed>|object $set = null ][, string $value = null ][, int $batchSize = 100 ]) : int
Parameters
$table : string

Table name.

$set : array<string|int, mixed>|object = null

(optional) Field name, or an associative array of field/value pairs.

$value : string = null

(optional) Field value, if $set is a single field.

$batchSize : int = 100

(optional) Count of rows to update at once. Default is 100.

Tags
example

Update multiple records by ID

$this->UserModel->update_batch('users', [
  ['id' => 1, 'status' => 'active'],
  ['id' => 2, 'status' => 'inactive'],
  ['id' => 3, 'status' => 'active']
], 'id');
Return values
int

Number of rows updated or FALSE on failure

where()

Generates the WHERE portion of the query. Separates multiple calls with 'AND'.

public where(string $key[, mixed $value = null ][, bool $escape = null ]) : Model
Parameters
$key : string

Name of field to compare, or associative array.

$value : mixed = null

(optional) If a single key, compared to this value.

$escape : bool = null

(optional) Whether to escape values and identifiers.

Tags
example

Simple equality

$users = $this->UserModel->where('status', 'active')->get_all();
// SELECT * FROM users WHERE status = 'active'
example

Comparison operators

$users = $this->UserModel
  ->where('age >=', 18)
  ->where('age <=', 65)
  ->get_all();
// SELECT * FROM users WHERE age >= 18 AND age <= 65
example

Multiple conditions with array

$users = $this->UserModel->where([
  'status' => 'active',
  'role' => 'admin'
])->get_all();
Return values
Model

where_in()

Generates a WHERE field IN('item', 'item') SQL query, joined with 'AND' if appropriate.

public where_in([string $key = null ][, array<string|int, mixed> $values = null ][, bool $escape = null ]) : Model
Parameters
$key : string = null

(optional) The field to search.

$values : array<string|int, mixed> = null

(optional) The values searched on.

$escape : bool = null

(optional) Whether to escape values and identifiers.

Tags
example

Filter by multiple IDs

$users = $this->UserModel
  ->where_in('id', [1, 5, 10, 15])
  ->get_all();
// SELECT * FROM users WHERE id IN (1, 5, 10, 15)
example

Filter by multiple statuses

$orders = $this->OrderModel
  ->where_in('status', ['pending', 'processing'])
  ->get_all();
Return values
Model

where_not_in()

Generates a WHERE field NOT IN('item', 'item') SQL query, joined with 'AND' if appropriate.

public where_not_in([string $key = null ][, array<string|int, mixed> $values = null ][, bool $escape = null ]) : Model
Parameters
$key : string = null

(optional) The field to search.

$values : array<string|int, mixed> = null

(optional) The values searched on.

$escape : bool = null

(optional) Whether to escape values and identifiers.

Return values
Model

        
On this page

Search results