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

codeigniter4 / CodeIgniter4 / 21164096296

20 Jan 2026 08:11AM UTC coverage: 85.526% (+0.002%) from 85.524%
21164096296

push

github

michalsn
Merge remote-tracking branch 'upstream/develop' into 4.7

# Conflicts:
#	utils/phpstan-baseline/empty.notAllowed.neon
#	utils/phpstan-baseline/loader.neon

11 of 11 new or added lines in 2 files covered. (100.0%)

7 existing lines in 2 files now uncovered.

21970 of 25688 relevant lines covered (85.53%)

206.21 hits per line

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

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

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

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

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

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

126
        if ($this->strictOn !== null) {
30✔
127
            if ($this->strictOn) {
30✔
128
                $this->mysqli->options(
1✔
129
                    MYSQLI_INIT_COMMAND,
1✔
130
                    "SET SESSION sql_mode = CONCAT(@@sql_mode, ',', 'STRICT_ALL_TABLES')",
1✔
131
                );
1✔
132
            } else {
133
                $this->mysqli->options(
29✔
134
                    MYSQLI_INIT_COMMAND,
29✔
135
                    "SET SESSION sql_mode = REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(
29✔
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', '')",
29✔
143
                );
29✔
144
            }
145
        }
146

147
        if (is_array($this->encrypt)) {
30✔
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) {
30✔
197
            $clientFlags += MYSQLI_CLIENT_FOUND_ROWS;
1✔
198
        }
199

200
        try {
201
            if ($this->mysqli->real_connect(
30✔
202
                $hostname,
30✔
203
                $this->username,
30✔
204
                $this->password,
30✔
205
                $this->database,
30✔
206
                $port,
30✔
207
                $socket,
30✔
208
                $clientFlags,
30✔
209
            )) {
30✔
210
                if (! $this->mysqli->set_charset($this->charset)) {
30✔
UNCOV
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;
30✔
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
     * Keep or establish the connection if no queries have been sent for
239
     * a length of time exceeding the server's idle timeout.
240
     *
241
     * @return void
242
     */
243
    public function reconnect()
244
    {
245
        $this->close();
×
246
        $this->initialize();
×
247
    }
248

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

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

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

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

275
            return true;
×
276
        }
277

278
        return false;
×
279
    }
280

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

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

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

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

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

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

326
        return false;
18✔
327
    }
328

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

340
        return $sql;
783✔
341
    }
342

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

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

360
        return $this->connID->real_escape_string($str);
757✔
361
    }
362

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

380
            return $str;
×
381
        }
382

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

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

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

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

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

411
        return $sql;
32✔
412
    }
413

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

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

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

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

447
        $retVal = [];
14✔
448

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

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

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

460
        return $retVal;
14✔
461
    }
462

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

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

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

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

485
        $keys = [];
7✔
486

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

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

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

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

508
        return $keys;
7✔
509
    }
510

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

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

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

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

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

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

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

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

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

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

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

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

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