Documentation

Connection extends BaseConnection
in package

Connection for MySQLi

Table of Contents

$connID  : object|resource|bool
Connection ID
$dataCache  : array<string|int, mixed>
Holds previously looked up data for performance reasons.
$DBDriver  : string
Database driver
$deleteHack  : bool
DELETE hack flag
$escapeChar  : string
Identifier escape character
$likeEscapeChar  : string
ESCAPE character
$likeEscapeStr  : string
ESCAPE statement string
$mysqli  : MySQLi
MySQLi object
$protectIdentifiers  : bool
Protect identifiers flag
$resultID  : object|resource|bool
Result ID
$transEnabled  : bool
Transaction enabled flag
$transStrict  : bool
Strict transaction mode flag
$aliasedTables  : array<string|int, mixed>
Array of table aliases.
$charset  : string
Character set
$compress  : bool
Compression flag
$connectDuration  : float
How long it took to establish connection.
$connectTime  : float
Microtime when connection was made
$database  : string
Database name
$DBCollat  : string
Collation
$DBDebug  : bool
Debug flag
$DBPrefix  : string
Table prefix
$DSN  : string
Data Source Name / Connect string
$encrypt  : mixed
Encryption flag/data
$failover  : array<string|int, mixed>
Settings for a failover connection.
$hostname  : string
Hostname
$lastQuery  : mixed
The last query object that was executed on this connection.
$password  : string
Password
$pConnect  : bool
Persistent connection flag
$port  : int|string
Database port
$pretend  : bool
If true, no queries will actually be ran against the database.
$queryClass  : string
Query Class
$reservedIdentifiers  : array<string|int, mixed>
List of reserved identifiers
$strictOn  : bool
Strict ON flag
$subdriver  : string
Sub-driver
$swapPre  : string
Swap Prefix
$transDepth  : int
Transaction depth level
$transFailure  : bool
Transaction failure flag
$transStatus  : bool
Transaction status flag
$username  : string
Username
__construct()  : mixed
Saves our connection settings.
__get()  : mixed
Accessor for properties if they exist.
__isset()  : bool
Checker for properties existence.
_fieldData()  : array<string|int, stdClass>
Returns an array of objects with field data
_foreignKeyData()  : array<string|int, stdClass>
Returns an array of objects with Foreign key data
_indexData()  : array<string|int, stdClass>
Returns an array of objects with index data
addTableAlias()  : $this
Add a table alias to our list.
affectedRows()  : int
Returns the total number of rows affected by this query.
callFunction()  : bool
This function enables you to call PHP database functions that are not natively included in CodeIgniter, in a platform independent manner.
close()  : void
Close the database connection.
connect()  : mixed
Connect to the database.
disableForeignKeyChecks()  : mixed
Disables foreign key checks temporarily.
enableForeignKeyChecks()  : mixed
Enables foreign key checks temporarily.
error()  : array<string, string|int>
Returns the last error code and message.
escape()  : mixed
"Smart" Escape String
escapeIdentifiers()  : mixed
Escape the SQL Identifiers
escapeLikeString()  : string|array<string|int, string>
Escape LIKE String
escapeLikeStringDirect()  : string|array<string|int, string>
Escape Like String Direct There are a few instances where MySQLi queries cannot take the additional "ESCAPE x" parameter for specifying the escape character in "LIKE" strings, and this handles those directly with a backslash.
escapeString()  : string|array<string|int, string>
Escape String
execute()  : mixed
Executes the query against the database.
fieldExists()  : bool
Determine if a particular field exists
getConnectDuration()  : string
Returns the number of seconds with microseconds that it took to connect to the database.
getConnection()  : mixed
Returns the actual connection object. If both a 'read' and 'write' connection has been specified, you can pass either term in to get that connection. If you pass either alias in and only a single connection is present, it must return the sole connection.
getConnectStart()  : float|null
Returns the time we started to connect to this database in seconds with microseconds.
getDatabase()  : string
Returns the name of the current database being used.
getFieldData()  : array<string|int, mixed>
Returns an object with field data
getFieldNames()  : array<string|int, mixed>|false
Fetch Field Names
getForeignKeyData()  : array<string|int, mixed>
Returns an object with foreign key data
getIndexData()  : array<string|int, mixed>
Returns an object with key data
getLastQuery()  : mixed
Returns the last query's statement object.
getPlatform()  : string
The name of the platform in use (MySQLi, mssql, etc)
getPrefix()  : string
Returns the database prefix.
getVersion()  : string
Returns a string containing the version of the database being used.
initialize()  : mixed|void
Initializes the database connection/settings.
insertID()  : int
Insert ID
isWriteType()  : bool
Determines if the statement is a write-type query or not.
listTables()  : bool|array<string|int, mixed>
Returns an array of table names
persistentConnect()  : mixed
Create a persistent database connection.
prefixTable()  : string
Prepends a database prefix if one exists in configuration
prepare()  : BasePreparedQuery|null
Creates a prepared statement with the database that can then be used to execute multiple statements against. Within the closure, you would build the query in any normal way, though the Query Builder is the expected manner.
pretend()  : $this
Allows the engine to be set into a mode where queries are not actually executed, but they are still generated, timed, etc.
protectIdentifiers()  : string|array<string|int, mixed>
Protect Identifiers
query()  : BaseResult|Query|bool
Orchestrates a query against the database. Queries must use Database\Statement objects to store the query and build it.
reconnect()  : void
Keep or establish the connection if no queries have been sent for a length of time exceeding the server's idle timeout.
resetDataCache()  : $this
Empties our data cache. Especially helpful during testing.
setAliasedTables()  : $this
Sets the Table Aliases to use. These are typically collected during use of the Builder, and set here so queries are built correctly.
setDatabase()  : bool
Select a specific database table to use.
setPrefix()  : string
Set DB Prefix
showLastQuery()  : string
Returns a string representation of the last query's statement object.
simpleQuery()  : mixed
Performs a basic query against the database. No binding or caching is performed, nor are transactions handled. Simply takes a raw query string and returns the database-specific result id.
table()  : BaseBuilder
Returns an instance of the query builder for this connection.
tableExists()  : bool
Determine if a particular table exists
transBegin()  : bool
Begin Transaction
transCommit()  : bool
Commit Transaction
transComplete()  : bool
Complete Transaction
transOff()  : void
Disable Transactions
transRollback()  : bool
Rollback Transaction
transStart()  : bool
Start Transaction
transStatus()  : bool
Lets you retrieve the transaction flag to determine if it has failed
transStrict()  : $this
Enable/disable Transaction Strict Mode
_close()  : void
Close the database connection.
_disableForeignKeyChecks()  : string
Returns platform-specific SQL to disable foreign key checks.
_enableForeignKeyChecks()  : string
Returns platform-specific SQL to enable foreign key checks.
_escapeString()  : string
Platform-dependant string escape
_listColumns()  : string
Generates a platform-specific query string so that the column names can be fetched.
_listTables()  : string
Generates the SQL for listing tables in a platform-dependent manner.
_transBegin()  : bool
Begin Transaction
_transCommit()  : bool
Commit Transaction
_transRollback()  : bool
Rollback Transaction
prepQuery()  : string
Prep the query

Properties

$connID

Connection ID

public object|resource|bool $connID = false

$dataCache

Holds previously looked up data for performance reasons.

public array<string|int, mixed> $dataCache = []

$DBDriver

Database driver

public string $DBDriver = 'MySQLi'

$deleteHack

DELETE hack flag

public bool $deleteHack = true

Whether to use the MySQL "delete hack" which allows the number of affected rows to be shown. Uses a preg_replace when enabled, adding a bit more processing to all queries.

$escapeChar

Identifier escape character

public string $escapeChar = '`'

$likeEscapeChar

ESCAPE character

public string $likeEscapeChar = '!'

$likeEscapeStr

ESCAPE statement string

public string $likeEscapeStr = " ESCAPE '%s' "

$mysqli

MySQLi object

public MySQLi $mysqli

Has to be preserved without being assigned to $conn_id.

$protectIdentifiers

Protect identifiers flag

public bool $protectIdentifiers = true

$resultID

Result ID

public object|resource|bool $resultID = false

$transEnabled

Transaction enabled flag

public bool $transEnabled = true

$transStrict

Strict transaction mode flag

public bool $transStrict = true

$aliasedTables

Array of table aliases.

protected array<string|int, mixed> $aliasedTables = []

$connectDuration

How long it took to establish connection.

protected float $connectDuration

$connectTime

Microtime when connection was made

protected float $connectTime

$DBCollat

Collation

protected string $DBCollat = 'utf8_general_ci'

$DBDebug

Debug flag

protected bool $DBDebug = false

Whether to display error messages.

$failover

Settings for a failover connection.

protected array<string|int, mixed> $failover = []

$lastQuery

The last query object that was executed on this connection.

protected mixed $lastQuery

$pConnect

Persistent connection flag

protected bool $pConnect = false

$pretend

If true, no queries will actually be ran against the database.

protected bool $pretend = false

$queryClass

Query Class

protected string $queryClass = 'CodeIgniter\Database\Query'

$reservedIdentifiers

List of reserved identifiers

protected array<string|int, mixed> $reservedIdentifiers = ['*']

Identifiers that must NOT be escaped.

$strictOn

Strict ON flag

protected bool $strictOn

Whether we're running in strict SQL mode.

$subdriver

Sub-driver

protected string $subdriver
Tags
used-by

CI_DB_pdo_driver

$transDepth

Transaction depth level

protected int $transDepth = 0

$transFailure

Transaction failure flag

protected bool $transFailure = false

Used with transactions to determine if a transaction has failed.

$transStatus

Transaction status flag

protected bool $transStatus = true

Used with transactions to determine if a rollback should occur.

Methods

__construct()

Saves our connection settings.

public __construct(array<string|int, mixed> $params) : mixed
Parameters
$params : array<string|int, mixed>
Return values
mixed

__get()

Accessor for properties if they exist.

public __get(string $key) : mixed
Parameters
$key : string
Return values
mixed

__isset()

Checker for properties existence.

public __isset(string $key) : bool
Parameters
$key : string
Return values
bool

_fieldData()

Returns an array of objects with field data

public _fieldData(string $table) : array<string|int, stdClass>
Parameters
$table : string
Tags
throws
DatabaseException
Return values
array<string|int, stdClass>

_foreignKeyData()

Returns an array of objects with Foreign key data

public _foreignKeyData(string $table) : array<string|int, stdClass>
Parameters
$table : string
Tags
throws
DatabaseException
Return values
array<string|int, stdClass>

_indexData()

Returns an array of objects with index data

public _indexData(string $table) : array<string|int, stdClass>
Parameters
$table : string
Tags
throws
DatabaseException
throws
LogicException
Return values
array<string|int, stdClass>

addTableAlias()

Add a table alias to our list.

public addTableAlias(string $table) : $this
Parameters
$table : string
Return values
$this

affectedRows()

Returns the total number of rows affected by this query.

public affectedRows() : int
Return values
int

callFunction()

This function enables you to call PHP database functions that are not natively included in CodeIgniter, in a platform independent manner.

public callFunction(string $functionName, array<string|int, mixed> ...$params) : bool
Parameters
$functionName : string
$params : array<string|int, mixed>
Tags
throws
DatabaseException
Return values
bool

close()

Close the database connection.

public close() : void
Return values
void

connect()

Connect to the database.

public connect([bool $persistent = false ]) : mixed
Parameters
$persistent : bool = false
Tags
throws
DatabaseException
Return values
mixed

disableForeignKeyChecks()

Disables foreign key checks temporarily.

public disableForeignKeyChecks() : mixed
Return values
mixed

enableForeignKeyChecks()

Enables foreign key checks temporarily.

public enableForeignKeyChecks() : mixed
Return values
mixed

error()

Returns the last error code and message.

public error() : array<string, string|int>

Must return this format: ['code' => string|int, 'message' => string] intval(code) === 0 means "no error".

Return values
array<string, string|int>

escape()

"Smart" Escape String

public escape(mixed $str) : mixed

Escapes data based on type. Sets boolean and null types

Parameters
$str : mixed
Return values
mixed

escapeIdentifiers()

Escape the SQL Identifiers

public escapeIdentifiers(mixed $item) : mixed

This function escapes column and table names

Parameters
$item : mixed
Return values
mixed

escapeLikeString()

Escape LIKE String

public escapeLikeString(string|array<string|int, string> $str) : string|array<string|int, string>

Calls the individual driver for platform specific escaping for LIKE conditions

Parameters
$str : string|array<string|int, string>
Return values
string|array<string|int, string>

escapeLikeStringDirect()

Escape Like String Direct There are a few instances where MySQLi queries cannot take the additional "ESCAPE x" parameter for specifying the escape character in "LIKE" strings, and this handles those directly with a backslash.

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

Input string

Return values
string|array<string|int, string>

escapeString()

Escape String

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

Input string

$like : bool = false

Whether or not the string will be used in a LIKE condition

Return values
string|array<string|int, string>

execute()

Executes the query against the database.

public execute(string $sql) : mixed
Parameters
$sql : string
Return values
mixed

fieldExists()

Determine if a particular field exists

public fieldExists(string $fieldName, string $tableName) : bool
Parameters
$fieldName : string
$tableName : string
Return values
bool

getConnectDuration()

Returns the number of seconds with microseconds that it took to connect to the database.

public getConnectDuration([int $decimals = 6 ]) : string

Used by the Debug Toolbar's timeline.

Parameters
$decimals : int = 6
Return values
string

getConnection()

Returns the actual connection object. If both a 'read' and 'write' connection has been specified, you can pass either term in to get that connection. If you pass either alias in and only a single connection is present, it must return the sole connection.

public getConnection([string|null $alias = null ]) : mixed
Parameters
$alias : string|null = null
Return values
mixed

getConnectStart()

Returns the time we started to connect to this database in seconds with microseconds.

public getConnectStart() : float|null

Used by the Debug Toolbar's timeline.

Return values
float|null

getDatabase()

Returns the name of the current database being used.

public getDatabase() : string
Return values
string

getFieldData()

Returns an object with field data

public getFieldData(string $table) : array<string|int, mixed>
Parameters
$table : string

the table name

Return values
array<string|int, mixed>

getFieldNames()

Fetch Field Names

public getFieldNames(string $table) : array<string|int, mixed>|false
Parameters
$table : string

Table name

Tags
throws
DatabaseException
Return values
array<string|int, mixed>|false

getForeignKeyData()

Returns an object with foreign key data

public getForeignKeyData(string $table) : array<string|int, mixed>
Parameters
$table : string

the table name

Return values
array<string|int, mixed>

getIndexData()

Returns an object with key data

public getIndexData(string $table) : array<string|int, mixed>
Parameters
$table : string

the table name

Return values
array<string|int, mixed>

getLastQuery()

Returns the last query's statement object.

public getLastQuery() : mixed
Return values
mixed

getPlatform()

The name of the platform in use (MySQLi, mssql, etc)

public getPlatform() : string
Return values
string

getPrefix()

Returns the database prefix.

public getPrefix() : string
Return values
string

getVersion()

Returns a string containing the version of the database being used.

public getVersion() : string
Return values
string

initialize()

Initializes the database connection/settings.

public initialize() : mixed|void
Tags
throws
DatabaseException
Return values
mixed|void

insertID()

Insert ID

public insertID() : int
Return values
int

isWriteType()

Determines if the statement is a write-type query or not.

public isWriteType(string $sql) : bool
Parameters
$sql : string
Return values
bool

listTables()

Returns an array of table names

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

= FALSE

Tags
throws
DatabaseException
Return values
bool|array<string|int, mixed>

persistentConnect()

Create a persistent database connection.

public persistentConnect() : mixed
Return values
mixed

prefixTable()

Prepends a database prefix if one exists in configuration

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

the table

Tags
throws
DatabaseException
Return values
string

prepare()

Creates a prepared statement with the database that can then be used to execute multiple statements against. Within the closure, you would build the query in any normal way, though the Query Builder is the expected manner.

public prepare(Closure $func[, array<string|int, mixed> $options = [] ]) : BasePreparedQuery|null

Example: $stmt = $db->prepare(function($db) { return $db->table('users') ->where('id', 1) ->get(); })

Parameters
$func : Closure
$options : array<string|int, mixed> = []

Passed to the prepare() method

Return values
BasePreparedQuery|null

pretend()

Allows the engine to be set into a mode where queries are not actually executed, but they are still generated, timed, etc.

public pretend([bool $pretend = true ]) : $this

This is primarily used by the prepared query functionality.

Parameters
$pretend : bool = true
Return values
$this

protectIdentifiers()

Protect Identifiers

public protectIdentifiers(string|array<string|int, mixed> $item[, bool $prefixSingle = false ][, bool $protectIdentifiers = null ][, bool $fieldExists = true ]) : string|array<string|int, mixed>

This function is used extensively by the Query Builder class, and by a couple functions in this class. It takes a column or table name (optionally with an alias) and inserts the table prefix onto it. Some logic is necessary in order to deal with column names that include the path. Consider a query like this:

SELECT hostname.database.table.column AS c FROM hostname.database.table

Or a query with aliasing:

SELECT m.member_id, m.member_name FROM members AS m

Since the column name can include up to four segments (host, DB, table, column) or also have an alias prefix, we need to do a bit of work to figure this out and insert the table prefix (if it exists) in the proper position, and escape only the correct identifiers.

Parameters
$item : string|array<string|int, mixed>
$prefixSingle : bool = false
$protectIdentifiers : bool = null
$fieldExists : bool = true
Return values
string|array<string|int, mixed>

query()

Orchestrates a query against the database. Queries must use Database\Statement objects to store the query and build it.

public query(string $sql[, mixed $binds = null ][, bool $setEscapeFlags = true ][, string $queryClass = '' ]) : BaseResult|Query|bool

This method works with the cache.

Should automatically handle different connections for read/write queries if needed.

Parameters
$sql : string
$binds : mixed = null
$setEscapeFlags : bool = true
$queryClass : string = ''
Tags
todo

BC set $queryClass default as null in 4.1

Return values
BaseResult|Query|bool

reconnect()

Keep or establish the connection if no queries have been sent for a length of time exceeding the server's idle timeout.

public reconnect() : void
Return values
void

resetDataCache()

Empties our data cache. Especially helpful during testing.

public resetDataCache() : $this
Return values
$this

setAliasedTables()

Sets the Table Aliases to use. These are typically collected during use of the Builder, and set here so queries are built correctly.

public setAliasedTables(array<string|int, mixed> $aliases) : $this
Parameters
$aliases : array<string|int, mixed>
Return values
$this

setDatabase()

Select a specific database table to use.

public setDatabase(string $databaseName) : bool
Parameters
$databaseName : string
Return values
bool

setPrefix()

Set DB Prefix

public setPrefix([string $prefix = '' ]) : string

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

Parameters
$prefix : string = ''

The prefix

Return values
string

showLastQuery()

Returns a string representation of the last query's statement object.

public showLastQuery() : string
Return values
string

simpleQuery()

Performs a basic query against the database. No binding or caching is performed, nor are transactions handled. Simply takes a raw query string and returns the database-specific result id.

public simpleQuery(string $sql) : mixed
Parameters
$sql : string
Return values
mixed

tableExists()

Determine if a particular table exists

public tableExists(string $tableName) : bool
Parameters
$tableName : string
Return values
bool

transBegin()

Begin Transaction

public transBegin([bool $testMode = false ]) : bool
Parameters
$testMode : bool = false
Return values
bool

transCommit()

Commit Transaction

public transCommit() : bool
Return values
bool

transComplete()

Complete Transaction

public transComplete() : bool
Return values
bool

transOff()

Disable Transactions

public transOff() : void

This permits transactions to be disabled at run-time.

Return values
void

transRollback()

Rollback Transaction

public transRollback() : bool
Return values
bool

transStart()

Start Transaction

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

= FALSE

Return values
bool

transStatus()

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

public transStatus() : bool
Return values
bool

transStrict()

Enable/disable Transaction Strict Mode

public transStrict([bool $mode = true ]) : $this

When strict mode is enabled, if you are running multiple groups of transactions, if one group fails all subsequent groups will be rolled back.

If strict mode is disabled, each group is treated autonomously, meaning a failure of one group will not affect any others

Parameters
$mode : bool = true

= true

Return values
$this

_close()

Close the database connection.

protected _close() : void
Return values
void

_disableForeignKeyChecks()

Returns platform-specific SQL to disable foreign key checks.

protected _disableForeignKeyChecks() : string
Return values
string

_enableForeignKeyChecks()

Returns platform-specific SQL to enable foreign key checks.

protected _enableForeignKeyChecks() : string
Return values
string

_escapeString()

Platform-dependant string escape

protected _escapeString(string $str) : string
Parameters
$str : string
Return values
string

_listColumns()

Generates a platform-specific query string so that the column names can be fetched.

protected _listColumns([string $table = '' ]) : string
Parameters
$table : string = ''
Return values
string

_listTables()

Generates the SQL for listing tables in a platform-dependent manner.

protected _listTables([bool $prefixLimit = false ]) : string

Uses escapeLikeStringDirect().

Parameters
$prefixLimit : bool = false
Return values
string

_transBegin()

Begin Transaction

protected _transBegin() : bool
Return values
bool

_transCommit()

Commit Transaction

protected _transCommit() : bool
Return values
bool

_transRollback()

Rollback Transaction

protected _transRollback() : bool
Return values
bool

prepQuery()

Prep the query

protected prepQuery(string $sql) : string

If needed, each database adapter can prep the query string

Parameters
$sql : string

an SQL query

Return values
string

Search results