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

codeigniter4 / CodeIgniter4 / 22314765112

23 Feb 2026 04:19PM UTC coverage: 86.645% (+0.04%) from 86.608%
22314765112

Pull #9986

github

web-flow
Merge 7a470bb1e into f733c6ed9
Pull Request #9986: refactor: remove deprecations in `Database`

1 of 1 new or added line in 1 file covered. (100.0%)

4 existing lines in 1 file now uncovered.

22234 of 25661 relevant lines covered (86.65%)

218.29 hits per line

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

69.61
/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] === '/') {
36✔
106
            $hostname = null;
×
107
            $port     = null;
×
108
            $socket   = $this->hostname;
×
109
        } else {
110
            $hostname = $persistent ? 'p:' . $this->hostname : $this->hostname;
36✔
111
            $port     = empty($this->port) ? null : $this->port;
36✔
112
            $socket   = '';
36✔
113
        }
114

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

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

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

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

126
        // Build init command for strictOn and timezone
127
        $initCommands = [];
36✔
128

129
        if ($this->strictOn !== null) {
36✔
UNCOV
130
            if ($this->strictOn) {
×
UNCOV
131
                $initCommands[] = "sql_mode = CONCAT(@@sql_mode, ',', 'STRICT_ALL_TABLES')";
×
132
            } else {
UNCOV
133
                $initCommands[] = "sql_mode = REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(
×
134
                                    @@sql_mode,
135
                                    'STRICT_ALL_TABLES,', ''),
136
                                ',STRICT_ALL_TABLES', ''),
137
                            'STRICT_ALL_TABLES', ''),
138
                        'STRICT_TRANS_TABLES,', ''),
139
                    ',STRICT_TRANS_TABLES', ''),
UNCOV
140
                'STRICT_TRANS_TABLES', '')";
×
141
            }
142
        }
143

144
        // Set session timezone if configured
145
        $timezoneOffset = $this->getSessionTimezone();
36✔
146
        if ($timezoneOffset !== null) {
36✔
147
            $initCommands[] = "time_zone = '{$timezoneOffset}'";
3✔
148
        }
149

150
        // Set init command if we have any commands
151
        if ($initCommands !== []) {
36✔
152
            $this->mysqli->options(
3✔
153
                MYSQLI_INIT_COMMAND,
3✔
154
                'SET SESSION ' . implode(', ', $initCommands),
3✔
155
            );
3✔
156
        }
157

158
        if (is_array($this->encrypt)) {
36✔
159
            $ssl = [];
×
160

161
            if (! empty($this->encrypt['ssl_key'])) {
×
162
                $ssl['key'] = $this->encrypt['ssl_key'];
×
163
            }
164
            if (! empty($this->encrypt['ssl_cert'])) {
×
165
                $ssl['cert'] = $this->encrypt['ssl_cert'];
×
166
            }
167
            if (! empty($this->encrypt['ssl_ca'])) {
×
168
                $ssl['ca'] = $this->encrypt['ssl_ca'];
×
169
            }
170
            if (! empty($this->encrypt['ssl_capath'])) {
×
171
                $ssl['capath'] = $this->encrypt['ssl_capath'];
×
172
            }
173
            if (! empty($this->encrypt['ssl_cipher'])) {
×
174
                $ssl['cipher'] = $this->encrypt['ssl_cipher'];
×
175
            }
176

177
            if ($ssl !== []) {
×
178
                if (isset($this->encrypt['ssl_verify'])) {
×
179
                    if ($this->encrypt['ssl_verify']) {
×
180
                        if (defined('MYSQLI_OPT_SSL_VERIFY_SERVER_CERT')) {
×
181
                            $this->mysqli->options(MYSQLI_OPT_SSL_VERIFY_SERVER_CERT, 1);
×
182
                        }
183
                    }
184
                    // Apparently (when it exists), setting MYSQLI_OPT_SSL_VERIFY_SERVER_CERT
185
                    // to FALSE didn't do anything, so PHP 5.6.16 introduced yet another
186
                    // constant ...
187
                    //
188
                    // https://secure.php.net/ChangeLog-5.php#5.6.16
189
                    // https://bugs.php.net/bug.php?id=68344
190
                    elseif (defined('MYSQLI_CLIENT_SSL_DONT_VERIFY_SERVER_CERT') && version_compare($this->mysqli->client_info, 'mysqlnd 5.6', '>=')) {
×
191
                        $clientFlags += MYSQLI_CLIENT_SSL_DONT_VERIFY_SERVER_CERT;
×
192
                    }
193
                }
194

195
                $this->mysqli->ssl_set(
×
196
                    $ssl['key'] ?? null,
×
197
                    $ssl['cert'] ?? null,
×
198
                    $ssl['ca'] ?? null,
×
199
                    $ssl['capath'] ?? null,
×
200
                    $ssl['cipher'] ?? null,
×
201
                );
×
202
            }
203

204
            $clientFlags += MYSQLI_CLIENT_SSL;
×
205
        }
206

207
        if ($this->foundRows) {
36✔
208
            $clientFlags += MYSQLI_CLIENT_FOUND_ROWS;
1✔
209
        }
210

211
        try {
212
            if ($this->mysqli->real_connect(
36✔
213
                $hostname,
36✔
214
                $this->username,
36✔
215
                $this->password,
36✔
216
                $this->database,
36✔
217
                $port,
36✔
218
                $socket,
36✔
219
                $clientFlags,
36✔
220
            )) {
36✔
221
                if (! $this->mysqli->set_charset($this->charset)) {
36✔
222
                    log_message('error', "Database: Unable to set the configured connection charset ('{$this->charset}').");
×
223

224
                    $this->mysqli->close();
×
225

226
                    if ($this->DBDebug) {
×
227
                        throw new DatabaseException('Unable to set client connection character set: ' . $this->charset);
×
228
                    }
229

230
                    return false;
×
231
                }
232

233
                return $this->mysqli;
36✔
234
            }
235
        } catch (Throwable $e) {
1✔
236
            // Clean sensitive information from errors.
237
            $msg = $e->getMessage();
1✔
238

239
            $msg = str_replace($this->username, '****', $msg);
1✔
240
            $msg = str_replace($this->password, '****', $msg);
1✔
241

242
            throw new DatabaseException($msg, $e->getCode(), $e);
1✔
243
        }
244

245
        return false;
×
246
    }
247

248
    /**
249
     * Close the database connection.
250
     *
251
     * @return void
252
     */
253
    protected function _close()
254
    {
255
        $this->connID->close();
3✔
256
    }
257

258
    /**
259
     * Select a specific database table to use.
260
     */
261
    public function setDatabase(string $databaseName): bool
262
    {
263
        if ($databaseName === '') {
×
264
            $databaseName = $this->database;
×
265
        }
266

267
        if (empty($this->connID)) {
×
268
            $this->initialize();
×
269
        }
270

271
        if ($this->connID->select_db($databaseName)) {
×
272
            $this->database = $databaseName;
×
273

274
            return true;
×
275
        }
276

277
        return false;
×
278
    }
279

280
    /**
281
     * Returns a string containing the version of the database being used.
282
     */
283
    public function getVersion(): string
284
    {
285
        if (isset($this->dataCache['version'])) {
4✔
286
            return $this->dataCache['version'];
3✔
287
        }
288

289
        if (empty($this->mysqli)) {
2✔
290
            $this->initialize();
1✔
291
        }
292

293
        return $this->dataCache['version'] = $this->mysqli->server_info;
2✔
294
    }
295

296
    /**
297
     * Executes the query against the database.
298
     *
299
     * @return false|mysqli_result
300
     */
301
    protected function execute(string $sql)
302
    {
303
        while ($this->connID->more_results()) {
802✔
304
            $this->connID->next_result();
×
305
            if ($res = $this->connID->store_result()) {
×
306
                $res->free();
×
307
            }
308
        }
309

310
        try {
311
            return $this->connID->query($this->prepQuery($sql), $this->resultMode);
802✔
312
        } catch (mysqli_sql_exception $e) {
32✔
313
            log_message('error', "{message}\nin {exFile} on line {exLine}.\n{trace}", [
32✔
314
                'message' => $e->getMessage(),
32✔
315
                'exFile'  => clean_path($e->getFile()),
32✔
316
                'exLine'  => $e->getLine(),
32✔
317
                'trace'   => render_backtrace($e->getTrace()),
32✔
318
            ]);
32✔
319

320
            if ($this->DBDebug) {
32✔
321
                throw new DatabaseException($e->getMessage(), $e->getCode(), $e);
14✔
322
            }
323
        }
324

325
        return false;
18✔
326
    }
327

328
    /**
329
     * Prep the query. If needed, each database adapter can prep the query string
330
     */
331
    protected function prepQuery(string $sql): string
332
    {
333
        // mysqli_affected_rows() returns 0 for "DELETE FROM TABLE" queries. This hack
334
        // modifies the query so that it a proper number of affected rows is returned.
335
        if ($this->deleteHack === true && preg_match('/^\s*DELETE\s+FROM\s+(\S+)\s*$/i', $sql)) {
802✔
336
            return trim($sql) . ' WHERE 1=1';
3✔
337
        }
338

339
        return $sql;
802✔
340
    }
341

342
    /**
343
     * Returns the total number of rows affected by this query.
344
     */
345
    public function affectedRows(): int
346
    {
347
        return $this->connID->affected_rows ?? 0;
62✔
348
    }
349

350
    /**
351
     * Platform-dependant string escape
352
     */
353
    protected function _escapeString(string $str): string
354
    {
355
        if (! $this->connID) {
773✔
356
            $this->initialize();
1✔
357
        }
358

359
        return $this->connID->real_escape_string($str);
773✔
360
    }
361

362
    /**
363
     * Escape Like String Direct
364
     * There are a few instances where MySQLi queries cannot take the
365
     * additional "ESCAPE x" parameter for specifying the escape character
366
     * in "LIKE" strings, and this handles those directly with a backslash.
367
     *
368
     * @param list<string>|string $str Input string
369
     *
370
     * @return list<string>|string
371
     */
372
    public function escapeLikeStringDirect($str)
373
    {
374
        if (is_array($str)) {
1✔
375
            foreach ($str as $key => $val) {
×
376
                $str[$key] = $this->escapeLikeStringDirect($val);
×
377
            }
378

379
            return $str;
×
380
        }
381

382
        $str = $this->_escapeString($str);
1✔
383

384
        // Escape LIKE condition wildcards
385
        return str_replace(
1✔
386
            [$this->likeEscapeChar, '%', '_'],
1✔
387
            ['\\' . $this->likeEscapeChar, '\\%', '\\_'],
1✔
388
            $str,
1✔
389
        );
1✔
390
    }
391

392
    /**
393
     * Generates the SQL for listing tables in a platform-dependent manner.
394
     * Uses escapeLikeStringDirect().
395
     *
396
     * @param string|null $tableName If $tableName is provided will return only this table if exists.
397
     */
398
    protected function _listTables(bool $prefixLimit = false, ?string $tableName = null): string
399
    {
400
        $sql = 'SHOW TABLES FROM ' . $this->escapeIdentifier($this->database);
717✔
401

402
        if ((string) $tableName !== '') {
717✔
403
            return $sql . ' LIKE ' . $this->escape($tableName);
716✔
404
        }
405

406
        if ($prefixLimit && $this->DBPrefix !== '') {
34✔
407
            return $sql . " LIKE '" . $this->escapeLikeStringDirect($this->DBPrefix) . "%'";
×
408
        }
409

410
        return $sql;
34✔
411
    }
412

413
    /**
414
     * Generates a platform-specific query string so that the column names can be fetched.
415
     *
416
     * @param string|TableName $table
417
     */
418
    protected function _listColumns($table = ''): string
419
    {
420
        $tableName = $this->protectIdentifiers(
8✔
421
            $table,
8✔
422
            true,
8✔
423
            null,
8✔
424
            false,
8✔
425
        );
8✔
426

427
        return 'SHOW COLUMNS FROM ' . $tableName;
8✔
428
    }
429

430
    /**
431
     * Returns an array of objects with field data
432
     *
433
     * @return list<stdClass>
434
     *
435
     * @throws DatabaseException
436
     */
437
    protected function _fieldData(string $table): array
438
    {
439
        $table = $this->protectIdentifiers($table, true, null, false);
14✔
440

441
        if (($query = $this->query('SHOW COLUMNS FROM ' . $table)) === false) {
14✔
442
            throw new DatabaseException(lang('Database.failGetFieldData'));
×
443
        }
444
        $query = $query->getResultObject();
14✔
445

446
        $retVal = [];
14✔
447

448
        for ($i = 0, $c = count($query); $i < $c; $i++) {
14✔
449
            $retVal[$i]       = new stdClass();
14✔
450
            $retVal[$i]->name = $query[$i]->Field;
14✔
451

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

454
            $retVal[$i]->nullable    = $query[$i]->Null === 'YES';
14✔
455
            $retVal[$i]->default     = $query[$i]->Default;
14✔
456
            $retVal[$i]->primary_key = (int) ($query[$i]->Key === 'PRI');
14✔
457
        }
458

459
        return $retVal;
14✔
460
    }
461

462
    /**
463
     * Returns an array of objects with index data
464
     *
465
     * @return array<string, stdClass>
466
     *
467
     * @throws DatabaseException
468
     * @throws LogicException
469
     */
470
    protected function _indexData(string $table): array
471
    {
472
        $table = $this->protectIdentifiers($table, true, null, false);
8✔
473

474
        if (($query = $this->query('SHOW INDEX FROM ' . $table)) === false) {
8✔
475
            throw new DatabaseException(lang('Database.failGetIndexData'));
×
476
        }
477

478
        $indexes = $query->getResultArray();
8✔
479

480
        if ($indexes === []) {
8✔
481
            return [];
3✔
482
        }
483

484
        $keys = [];
7✔
485

486
        foreach ($indexes as $index) {
7✔
487
            if (empty($keys[$index['Key_name']])) {
7✔
488
                $keys[$index['Key_name']]       = new stdClass();
7✔
489
                $keys[$index['Key_name']]->name = $index['Key_name'];
7✔
490

491
                if ($index['Key_name'] === 'PRIMARY') {
7✔
492
                    $type = 'PRIMARY';
5✔
493
                } elseif ($index['Index_type'] === 'FULLTEXT') {
5✔
494
                    $type = 'FULLTEXT';
×
495
                } elseif ($index['Non_unique']) {
5✔
496
                    $type = $index['Index_type'] === 'SPATIAL' ? 'SPATIAL' : 'INDEX';
5✔
497
                } else {
498
                    $type = 'UNIQUE';
3✔
499
                }
500

501
                $keys[$index['Key_name']]->type = $type;
7✔
502
            }
503

504
            $keys[$index['Key_name']]->fields[] = $index['Column_name'];
7✔
505
        }
506

507
        return $keys;
7✔
508
    }
509

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

541
        if (($query = $this->query($sql)) === false) {
6✔
542
            throw new DatabaseException(lang('Database.failGetForeignKeyData'));
×
543
        }
544

545
        $query   = $query->getResultObject();
6✔
546
        $indexes = [];
6✔
547

548
        foreach ($query as $row) {
6✔
549
            $indexes[$row->CONSTRAINT_NAME]['constraint_name']       = $row->CONSTRAINT_NAME;
5✔
550
            $indexes[$row->CONSTRAINT_NAME]['table_name']            = $row->TABLE_NAME;
5✔
551
            $indexes[$row->CONSTRAINT_NAME]['column_name'][]         = $row->COLUMN_NAME;
5✔
552
            $indexes[$row->CONSTRAINT_NAME]['foreign_table_name']    = $row->REFERENCED_TABLE_NAME;
5✔
553
            $indexes[$row->CONSTRAINT_NAME]['foreign_column_name'][] = $row->REFERENCED_COLUMN_NAME;
5✔
554
            $indexes[$row->CONSTRAINT_NAME]['on_delete']             = $row->DELETE_RULE;
5✔
555
            $indexes[$row->CONSTRAINT_NAME]['on_update']             = $row->UPDATE_RULE;
5✔
556
            $indexes[$row->CONSTRAINT_NAME]['match']                 = $row->MATCH_OPTION;
5✔
557
        }
558

559
        return $this->foreignKeyDataToObjects($indexes);
6✔
560
    }
561

562
    /**
563
     * Returns platform-specific SQL to disable foreign key checks.
564
     *
565
     * @return string
566
     */
567
    protected function _disableForeignKeyChecks()
568
    {
569
        return 'SET FOREIGN_KEY_CHECKS=0';
722✔
570
    }
571

572
    /**
573
     * Returns platform-specific SQL to enable foreign key checks.
574
     *
575
     * @return string
576
     */
577
    protected function _enableForeignKeyChecks()
578
    {
579
        return 'SET FOREIGN_KEY_CHECKS=1';
722✔
580
    }
581

582
    /**
583
     * Returns the last error code and message.
584
     * Must return this format: ['code' => string|int, 'message' => string]
585
     * intval(code) === 0 means "no error".
586
     *
587
     * @return array<string, int|string>
588
     */
589
    public function error(): array
590
    {
591
        if (! empty($this->mysqli->connect_errno)) {
2✔
592
            return [
×
593
                'code'    => $this->mysqli->connect_errno,
×
594
                'message' => $this->mysqli->connect_error,
×
595
            ];
×
596
        }
597

598
        return [
2✔
599
            'code'    => $this->connID->errno,
2✔
600
            'message' => $this->connID->error,
2✔
601
        ];
2✔
602
    }
603

604
    /**
605
     * Insert ID
606
     */
607
    public function insertID(): int
608
    {
609
        return $this->connID->insert_id;
83✔
610
    }
611

612
    /**
613
     * Begin Transaction
614
     */
615
    protected function _transBegin(): bool
616
    {
617
        return $this->connID->begin_transaction();
19✔
618
    }
619

620
    /**
621
     * Commit Transaction
622
     */
623
    protected function _transCommit(): bool
624
    {
625
        return $this->connID->commit();
5✔
626
    }
627

628
    /**
629
     * Rollback Transaction
630
     */
631
    protected function _transRollback(): bool
632
    {
633
        return $this->connID->rollback();
19✔
634
    }
635
}
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