• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

codeigniter4 / CodeIgniter4 / 22361824225

24 Feb 2026 05:14PM UTC coverage: 85.71% (-0.02%) from 85.734%
22361824225

push

github

web-flow
test: turn `MySQLi` `$strictOn` to `true` by default (#9996)

22271 of 25984 relevant lines covered (85.71%)

206.51 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

68.16
/system/Database/MySQLi/Connection.php
1
<?php
2

3
declare(strict_types=1);
4

5
/**
6
 * This file is part of CodeIgniter 4 framework.
7
 *
8
 * (c) CodeIgniter Foundation <admin@codeigniter.com>
9
 *
10
 * For the full copyright and license information, please view
11
 * the LICENSE file that was distributed with this source code.
12
 */
13

14
namespace CodeIgniter\Database\MySQLi;
15

16
use CodeIgniter\Database\BaseConnection;
17
use CodeIgniter\Database\Exceptions\DatabaseException;
18
use CodeIgniter\Database\TableName;
19
use CodeIgniter\Exceptions\LogicException;
20
use mysqli;
21
use mysqli_result;
22
use mysqli_sql_exception;
23
use stdClass;
24
use Throwable;
25

26
/**
27
 * Connection for MySQLi
28
 *
29
 * @extends BaseConnection<mysqli, mysqli_result>
30
 */
31
class Connection extends BaseConnection
32
{
33
    /**
34
     * Database driver
35
     *
36
     * @var string
37
     */
38
    public $DBDriver = 'MySQLi';
39

40
    /**
41
     * DELETE hack flag
42
     *
43
     * Whether to use the MySQL "delete hack" which allows the number
44
     * of affected rows to be shown. Uses a preg_replace when enabled,
45
     * adding a bit more processing to all queries.
46
     *
47
     * @var bool
48
     */
49
    public $deleteHack = true;
50

51
    /**
52
     * Identifier escape character
53
     *
54
     * @var string
55
     */
56
    public $escapeChar = '`';
57

58
    /**
59
     * MySQLi object
60
     *
61
     * Has to be preserved without being assigned to $connId.
62
     *
63
     * @var false|mysqli
64
     */
65
    public $mysqli;
66

67
    /**
68
     * MySQLi constant
69
     *
70
     * For unbuffered queries use `MYSQLI_USE_RESULT`.
71
     *
72
     * Default mode for buffered queries uses `MYSQLI_STORE_RESULT`.
73
     *
74
     * @var int
75
     */
76
    public $resultMode = MYSQLI_STORE_RESULT;
77

78
    /**
79
     * Use MYSQLI_OPT_INT_AND_FLOAT_NATIVE
80
     *
81
     * @var bool
82
     */
83
    public $numberNative = false;
84

85
    /**
86
     * Use MYSQLI_CLIENT_FOUND_ROWS
87
     *
88
     * Whether affectedRows() should return number of rows found,
89
     * or number of rows changed, after an UPDATE query.
90
     *
91
     * @var bool
92
     */
93
    public $foundRows = false;
94

95
    /**
96
     * Connect to the database.
97
     *
98
     * @return false|mysqli
99
     *
100
     * @throws DatabaseException
101
     */
102
    public function connect(bool $persistent = false)
103
    {
104
        // Do we have a socket path?
105
        if ($this->hostname[0] === '/') {
32✔
106
            $hostname = null;
×
107
            $port     = null;
×
108
            $socket   = $this->hostname;
×
109
        } else {
110
            $hostname = $persistent ? 'p:' . $this->hostname : $this->hostname;
32✔
111
            $port     = empty($this->port) ? null : $this->port;
32✔
112
            $socket   = '';
32✔
113
        }
114

115
        $clientFlags  = ($this->compress === true) ? MYSQLI_CLIENT_COMPRESS : 0;
32✔
116
        $this->mysqli = mysqli_init();
32✔
117

118
        mysqli_report(MYSQLI_REPORT_ALL & ~MYSQLI_REPORT_INDEX);
32✔
119

120
        $this->mysqli->options(MYSQLI_OPT_CONNECT_TIMEOUT, 10);
32✔
121

122
        if ($this->numberNative === true) {
32✔
123
            $this->mysqli->options(MYSQLI_OPT_INT_AND_FLOAT_NATIVE, 1);
1✔
124
        }
125

126
        if ($this->strictOn !== null) {
32✔
127
            if ($this->strictOn) {
32✔
128
                $this->mysqli->options(
32✔
129
                    MYSQLI_INIT_COMMAND,
32✔
130
                    "SET SESSION sql_mode = CONCAT(@@sql_mode, ',', 'STRICT_ALL_TABLES')",
32✔
131
                );
32✔
132
            } else {
133
                $this->mysqli->options(
×
134
                    MYSQLI_INIT_COMMAND,
×
135
                    "SET SESSION sql_mode = REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(
×
136
                                        @@sql_mode,
137
                                        'STRICT_ALL_TABLES,', ''),
138
                                    ',STRICT_ALL_TABLES', ''),
139
                                'STRICT_ALL_TABLES', ''),
140
                            'STRICT_TRANS_TABLES,', ''),
141
                        ',STRICT_TRANS_TABLES', ''),
142
                    'STRICT_TRANS_TABLES', '')",
×
143
                );
×
144
            }
145
        }
146

147
        if (is_array($this->encrypt)) {
32✔
148
            $ssl = [];
×
149

150
            if (! empty($this->encrypt['ssl_key'])) {
×
151
                $ssl['key'] = $this->encrypt['ssl_key'];
×
152
            }
153
            if (! empty($this->encrypt['ssl_cert'])) {
×
154
                $ssl['cert'] = $this->encrypt['ssl_cert'];
×
155
            }
156
            if (! empty($this->encrypt['ssl_ca'])) {
×
157
                $ssl['ca'] = $this->encrypt['ssl_ca'];
×
158
            }
159
            if (! empty($this->encrypt['ssl_capath'])) {
×
160
                $ssl['capath'] = $this->encrypt['ssl_capath'];
×
161
            }
162
            if (! empty($this->encrypt['ssl_cipher'])) {
×
163
                $ssl['cipher'] = $this->encrypt['ssl_cipher'];
×
164
            }
165

166
            if ($ssl !== []) {
×
167
                if (isset($this->encrypt['ssl_verify'])) {
×
168
                    if ($this->encrypt['ssl_verify']) {
×
169
                        if (defined('MYSQLI_OPT_SSL_VERIFY_SERVER_CERT')) {
×
170
                            $this->mysqli->options(MYSQLI_OPT_SSL_VERIFY_SERVER_CERT, 1);
×
171
                        }
172
                    }
173
                    // Apparently (when it exists), setting MYSQLI_OPT_SSL_VERIFY_SERVER_CERT
174
                    // to FALSE didn't do anything, so PHP 5.6.16 introduced yet another
175
                    // constant ...
176
                    //
177
                    // https://secure.php.net/ChangeLog-5.php#5.6.16
178
                    // https://bugs.php.net/bug.php?id=68344
179
                    elseif (defined('MYSQLI_CLIENT_SSL_DONT_VERIFY_SERVER_CERT') && version_compare($this->mysqli->client_info, 'mysqlnd 5.6', '>=')) {
×
180
                        $clientFlags += MYSQLI_CLIENT_SSL_DONT_VERIFY_SERVER_CERT;
×
181
                    }
182
                }
183

184
                $this->mysqli->ssl_set(
×
185
                    $ssl['key'] ?? null,
×
186
                    $ssl['cert'] ?? null,
×
187
                    $ssl['ca'] ?? null,
×
188
                    $ssl['capath'] ?? null,
×
189
                    $ssl['cipher'] ?? null,
×
190
                );
×
191
            }
192

193
            $clientFlags += MYSQLI_CLIENT_SSL;
×
194
        }
195

196
        if ($this->foundRows) {
32✔
197
            $clientFlags += MYSQLI_CLIENT_FOUND_ROWS;
1✔
198
        }
199

200
        try {
201
            if ($this->mysqli->real_connect(
32✔
202
                $hostname,
32✔
203
                $this->username,
32✔
204
                $this->password,
32✔
205
                $this->database,
32✔
206
                $port,
32✔
207
                $socket,
32✔
208
                $clientFlags,
32✔
209
            )) {
32✔
210
                if (! $this->mysqli->set_charset($this->charset)) {
32✔
211
                    log_message('error', "Database: Unable to set the configured connection charset ('{$this->charset}').");
×
212

213
                    $this->mysqli->close();
×
214

215
                    if ($this->DBDebug) {
×
216
                        throw new DatabaseException('Unable to set client connection character set: ' . $this->charset);
×
217
                    }
218

219
                    return false;
×
220
                }
221

222
                return $this->mysqli;
32✔
223
            }
224
        } catch (Throwable $e) {
1✔
225
            // Clean sensitive information from errors.
226
            $msg = $e->getMessage();
1✔
227

228
            $msg = str_replace($this->username, '****', $msg);
1✔
229
            $msg = str_replace($this->password, '****', $msg);
1✔
230

231
            throw new DatabaseException($msg, $e->getCode(), $e);
1✔
232
        }
233

234
        return false;
×
235
    }
236

237
    /**
238
     * Close the database connection.
239
     *
240
     * @return void
241
     */
242
    protected function _close()
243
    {
244
        $this->connID->close();
3✔
245
    }
246

247
    /**
248
     * Select a specific database table to use.
249
     */
250
    public function setDatabase(string $databaseName): bool
251
    {
252
        if ($databaseName === '') {
×
253
            $databaseName = $this->database;
×
254
        }
255

256
        if (empty($this->connID)) {
×
257
            $this->initialize();
×
258
        }
259

260
        if ($this->connID->select_db($databaseName)) {
×
261
            $this->database = $databaseName;
×
262

263
            return true;
×
264
        }
265

266
        return false;
×
267
    }
268

269
    /**
270
     * Returns a string containing the version of the database being used.
271
     */
272
    public function getVersion(): string
273
    {
274
        if (isset($this->dataCache['version'])) {
4✔
275
            return $this->dataCache['version'];
3✔
276
        }
277

278
        if (empty($this->mysqli)) {
2✔
279
            $this->initialize();
1✔
280
        }
281

282
        return $this->dataCache['version'] = $this->mysqli->server_info;
2✔
283
    }
284

285
    /**
286
     * Executes the query against the database.
287
     *
288
     * @return false|mysqli_result
289
     */
290
    protected function execute(string $sql)
291
    {
292
        while ($this->connID->more_results()) {
795✔
293
            $this->connID->next_result();
×
294
            if ($res = $this->connID->store_result()) {
×
295
                $res->free();
×
296
            }
297
        }
298

299
        try {
300
            return $this->connID->query($this->prepQuery($sql), $this->resultMode);
795✔
301
        } catch (mysqli_sql_exception $e) {
32✔
302
            log_message('error', "{message}\nin {exFile} on line {exLine}.\n{trace}", [
32✔
303
                'message' => $e->getMessage(),
32✔
304
                'exFile'  => clean_path($e->getFile()),
32✔
305
                'exLine'  => $e->getLine(),
32✔
306
                'trace'   => render_backtrace($e->getTrace()),
32✔
307
            ]);
32✔
308

309
            if ($this->DBDebug) {
32✔
310
                throw new DatabaseException($e->getMessage(), $e->getCode(), $e);
14✔
311
            }
312
        }
313

314
        return false;
18✔
315
    }
316

317
    /**
318
     * Prep the query. If needed, each database adapter can prep the query string
319
     */
320
    protected function prepQuery(string $sql): string
321
    {
322
        // mysqli_affected_rows() returns 0 for "DELETE FROM TABLE" queries. This hack
323
        // modifies the query so that it a proper number of affected rows is returned.
324
        if ($this->deleteHack === true && preg_match('/^\s*DELETE\s+FROM\s+(\S+)\s*$/i', $sql)) {
795✔
325
            return trim($sql) . ' WHERE 1=1';
3✔
326
        }
327

328
        return $sql;
795✔
329
    }
330

331
    /**
332
     * Returns the total number of rows affected by this query.
333
     */
334
    public function affectedRows(): int
335
    {
336
        return $this->connID->affected_rows ?? 0;
64✔
337
    }
338

339
    /**
340
     * Platform-dependant string escape
341
     */
342
    protected function _escapeString(string $str): string
343
    {
344
        if (! $this->connID) {
766✔
345
            $this->initialize();
×
346
        }
347

348
        return $this->connID->real_escape_string($str);
766✔
349
    }
350

351
    /**
352
     * Escape Like String Direct
353
     * There are a few instances where MySQLi queries cannot take the
354
     * additional "ESCAPE x" parameter for specifying the escape character
355
     * in "LIKE" strings, and this handles those directly with a backslash.
356
     *
357
     * @param list<string>|string $str Input string
358
     *
359
     * @return list<string>|string
360
     */
361
    public function escapeLikeStringDirect($str)
362
    {
363
        if (is_array($str)) {
1✔
364
            foreach ($str as $key => $val) {
×
365
                $str[$key] = $this->escapeLikeStringDirect($val);
×
366
            }
367

368
            return $str;
×
369
        }
370

371
        $str = $this->_escapeString($str);
1✔
372

373
        // Escape LIKE condition wildcards
374
        return str_replace(
1✔
375
            [$this->likeEscapeChar, '%', '_'],
1✔
376
            ['\\' . $this->likeEscapeChar, '\\%', '\\_'],
1✔
377
            $str,
1✔
378
        );
1✔
379
    }
380

381
    /**
382
     * Generates the SQL for listing tables in a platform-dependent manner.
383
     * Uses escapeLikeStringDirect().
384
     *
385
     * @param string|null $tableName If $tableName is provided will return only this table if exists.
386
     */
387
    protected function _listTables(bool $prefixLimit = false, ?string $tableName = null): string
388
    {
389
        $sql = 'SHOW TABLES FROM ' . $this->escapeIdentifier($this->database);
710✔
390

391
        if ((string) $tableName !== '') {
710✔
392
            return $sql . ' LIKE ' . $this->escape($tableName);
709✔
393
        }
394

395
        if ($prefixLimit && $this->DBPrefix !== '') {
34✔
396
            return $sql . " LIKE '" . $this->escapeLikeStringDirect($this->DBPrefix) . "%'";
×
397
        }
398

399
        return $sql;
34✔
400
    }
401

402
    /**
403
     * Generates a platform-specific query string so that the column names can be fetched.
404
     *
405
     * @param string|TableName $table
406
     */
407
    protected function _listColumns($table = ''): string
408
    {
409
        $tableName = $this->protectIdentifiers(
8✔
410
            $table,
8✔
411
            true,
8✔
412
            null,
8✔
413
            false,
8✔
414
        );
8✔
415

416
        return 'SHOW COLUMNS FROM ' . $tableName;
8✔
417
    }
418

419
    /**
420
     * Returns an array of objects with field data
421
     *
422
     * @return list<stdClass>
423
     *
424
     * @throws DatabaseException
425
     */
426
    protected function _fieldData(string $table): array
427
    {
428
        $table = $this->protectIdentifiers($table, true, null, false);
14✔
429

430
        if (($query = $this->query('SHOW COLUMNS FROM ' . $table)) === false) {
14✔
431
            throw new DatabaseException(lang('Database.failGetFieldData'));
×
432
        }
433
        $query = $query->getResultObject();
14✔
434

435
        $retVal = [];
14✔
436

437
        for ($i = 0, $c = count($query); $i < $c; $i++) {
14✔
438
            $retVal[$i]       = new stdClass();
14✔
439
            $retVal[$i]->name = $query[$i]->Field;
14✔
440

441
            sscanf($query[$i]->Type, '%[a-z](%d)', $retVal[$i]->type, $retVal[$i]->max_length);
14✔
442

443
            $retVal[$i]->nullable    = $query[$i]->Null === 'YES';
14✔
444
            $retVal[$i]->default     = $query[$i]->Default;
14✔
445
            $retVal[$i]->primary_key = (int) ($query[$i]->Key === 'PRI');
14✔
446
        }
447

448
        return $retVal;
14✔
449
    }
450

451
    /**
452
     * Returns an array of objects with index data
453
     *
454
     * @return array<string, stdClass>
455
     *
456
     * @throws DatabaseException
457
     * @throws LogicException
458
     */
459
    protected function _indexData(string $table): array
460
    {
461
        $table = $this->protectIdentifiers($table, true, null, false);
8✔
462

463
        if (($query = $this->query('SHOW INDEX FROM ' . $table)) === false) {
8✔
464
            throw new DatabaseException(lang('Database.failGetIndexData'));
×
465
        }
466

467
        $indexes = $query->getResultArray();
8✔
468

469
        if ($indexes === []) {
8✔
470
            return [];
3✔
471
        }
472

473
        $keys = [];
7✔
474

475
        foreach ($indexes as $index) {
7✔
476
            if (empty($keys[$index['Key_name']])) {
7✔
477
                $keys[$index['Key_name']]       = new stdClass();
7✔
478
                $keys[$index['Key_name']]->name = $index['Key_name'];
7✔
479

480
                if ($index['Key_name'] === 'PRIMARY') {
7✔
481
                    $type = 'PRIMARY';
5✔
482
                } elseif ($index['Index_type'] === 'FULLTEXT') {
5✔
483
                    $type = 'FULLTEXT';
×
484
                } elseif ($index['Non_unique']) {
5✔
485
                    $type = $index['Index_type'] === 'SPATIAL' ? 'SPATIAL' : 'INDEX';
5✔
486
                } else {
487
                    $type = 'UNIQUE';
3✔
488
                }
489

490
                $keys[$index['Key_name']]->type = $type;
7✔
491
            }
492

493
            $keys[$index['Key_name']]->fields[] = $index['Column_name'];
7✔
494
        }
495

496
        return $keys;
7✔
497
    }
498

499
    /**
500
     * Returns an array of objects with Foreign key data
501
     *
502
     * @return array<string, stdClass>
503
     *
504
     * @throws DatabaseException
505
     */
506
    protected function _foreignKeyData(string $table): array
507
    {
508
        $sql = '
6✔
509
                SELECT
510
                    tc.CONSTRAINT_NAME,
511
                    tc.TABLE_NAME,
512
                    kcu.COLUMN_NAME,
513
                    rc.REFERENCED_TABLE_NAME,
514
                    kcu.REFERENCED_COLUMN_NAME,
515
                    rc.DELETE_RULE,
516
                    rc.UPDATE_RULE,
517
                    rc.MATCH_OPTION
518
                FROM information_schema.table_constraints AS tc
519
                INNER JOIN information_schema.referential_constraints AS rc
520
                    ON tc.constraint_name = rc.constraint_name
521
                    AND tc.constraint_schema = rc.constraint_schema
522
                INNER JOIN information_schema.key_column_usage AS kcu
523
                    ON tc.constraint_name = kcu.constraint_name
524
                    AND tc.constraint_schema = kcu.constraint_schema
525
                WHERE
526
                    tc.constraint_type = ' . $this->escape('FOREIGN KEY') . ' AND
6✔
527
                    tc.table_schema = ' . $this->escape($this->database) . ' AND
6✔
528
                    tc.table_name = ' . $this->escape($table);
6✔
529

530
        if (($query = $this->query($sql)) === false) {
6✔
531
            throw new DatabaseException(lang('Database.failGetForeignKeyData'));
×
532
        }
533

534
        $query   = $query->getResultObject();
6✔
535
        $indexes = [];
6✔
536

537
        foreach ($query as $row) {
6✔
538
            $indexes[$row->CONSTRAINT_NAME]['constraint_name']       = $row->CONSTRAINT_NAME;
5✔
539
            $indexes[$row->CONSTRAINT_NAME]['table_name']            = $row->TABLE_NAME;
5✔
540
            $indexes[$row->CONSTRAINT_NAME]['column_name'][]         = $row->COLUMN_NAME;
5✔
541
            $indexes[$row->CONSTRAINT_NAME]['foreign_table_name']    = $row->REFERENCED_TABLE_NAME;
5✔
542
            $indexes[$row->CONSTRAINT_NAME]['foreign_column_name'][] = $row->REFERENCED_COLUMN_NAME;
5✔
543
            $indexes[$row->CONSTRAINT_NAME]['on_delete']             = $row->DELETE_RULE;
5✔
544
            $indexes[$row->CONSTRAINT_NAME]['on_update']             = $row->UPDATE_RULE;
5✔
545
            $indexes[$row->CONSTRAINT_NAME]['match']                 = $row->MATCH_OPTION;
5✔
546
        }
547

548
        return $this->foreignKeyDataToObjects($indexes);
6✔
549
    }
550

551
    /**
552
     * Returns platform-specific SQL to disable foreign key checks.
553
     *
554
     * @return string
555
     */
556
    protected function _disableForeignKeyChecks()
557
    {
558
        return 'SET FOREIGN_KEY_CHECKS=0';
715✔
559
    }
560

561
    /**
562
     * Returns platform-specific SQL to enable foreign key checks.
563
     *
564
     * @return string
565
     */
566
    protected function _enableForeignKeyChecks()
567
    {
568
        return 'SET FOREIGN_KEY_CHECKS=1';
715✔
569
    }
570

571
    /**
572
     * Returns the last error code and message.
573
     * Must return this format: ['code' => string|int, 'message' => string]
574
     * intval(code) === 0 means "no error".
575
     *
576
     * @return array<string, int|string>
577
     */
578
    public function error(): array
579
    {
580
        if (! empty($this->mysqli->connect_errno)) {
2✔
581
            return [
×
582
                'code'    => $this->mysqli->connect_errno,
×
583
                'message' => $this->mysqli->connect_error,
×
584
            ];
×
585
        }
586

587
        return [
2✔
588
            'code'    => $this->connID->errno,
2✔
589
            'message' => $this->connID->error,
2✔
590
        ];
2✔
591
    }
592

593
    /**
594
     * Insert ID
595
     */
596
    public function insertID(): int
597
    {
598
        return $this->connID->insert_id;
83✔
599
    }
600

601
    /**
602
     * Begin Transaction
603
     */
604
    protected function _transBegin(): bool
605
    {
606
        return $this->connID->begin_transaction();
19✔
607
    }
608

609
    /**
610
     * Commit Transaction
611
     */
612
    protected function _transCommit(): bool
613
    {
614
        return $this->connID->commit();
5✔
615
    }
616

617
    /**
618
     * Rollback Transaction
619
     */
620
    protected function _transRollback(): bool
621
    {
622
        return $this->connID->rollback();
19✔
623
    }
624
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc