Test Failed
Push — master ( 68b8b4...8b6eb2 )
by Joe
16:28
created

Db::transactionCommit()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 1
CRAP Score 3

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 3
eloc 3
c 2
b 0
f 0
nc 2
nop 0
dl 0
loc 6
ccs 1
cts 1
cp 1
crap 3
rs 10
1
<?php
2
/**
3
* MySQL Related Functionality
4
* @author Joe Huss <[email protected]>
5
* @copyright 2025
6
* @package MyAdmin
7
* @category SQL
8
*/
9
10
namespace MyDb\Mysqli;
11
12
use MyDb\Generic;
13
use MyDb\Db_Interface;
14
15
/**
16
* Db
17
*
18
* @access public
19
*/
20
class Db extends Generic implements Db_Interface
21
{
22
    /**
23
    * @var string
24
    */
25
    public $type = 'mysqli';
26
    public $statement;
27
    public $statement_query;
28
    public $statement_vars;
29
30
    /**
31
    * alias function of select_db, changes the database we are working with.
32
    *
33 1
    * @param string $database the name of the database to use
34
    * @return void
35 1
    */
36
    public function useDb($database)
37
    {
38
        $this->selectDb($database);
39
    }
40
41
    /**
42
    * changes the database we are working with.
43
    *
44 1
    * @param string $database the name of the database to use
45
    * @return void
46 1
    */
47 1
    public function selectDb($database)
48
    {
49
        $this->connect();
50
        mysqli_select_db($this->linkId, $database);
51
    }
52
53
    /* public: connection management */
54
55
    /**
56
    * Db::connect()
57
    * @param string $database
58
    * @param string $host
59
    * @param string $user
60 26
    * @param string $password
61
    * @return int|\mysqli
62
    */
63 26
    public function connect($database = '', $host = '', $user = '', $password = '', $port = '')
64 26
    {
65
        /* Handle defaults */
66 26
        if ($database == '') {
67 26
            $database = $this->database;
68
        }
69 26
        if ($host == '') {
70 26
            $host = $this->host;
71
        }
72 26
        if ($user == '') {
73 26
            $user = $this->user;
74
        }
75 26
        if ($password == '') {
76 26
            $password = $this->password;
77
        }
78
        if ($port == '') {
79 26
            $port = $this->port;
80 26
        }
81 26
        /* establish connection, select database */
82 6
        if (!is_object($this->linkId)) {
83
            $this->connectionAttempt++;
84 26
            if ($this->connectionAttempt >= $this->maxConnectErrors - 1) {
85
                error_log("MySQLi Connection Attempt #{$this->connectionAttempt}/{$this->maxConnectErrors}");
86
                exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
87
            }
88 26
            if ($this->connectionAttempt >= $this->maxConnectErrors) {
89 26
                $this->halt("connect($host, $user, \$password) failed. ".(is_object($this->linkId) && isset( $this->linkId->connect_error) ? $this->linkId->connect_error : ''));
0 ignored issues
show
introduced by
The condition is_object($this->linkId) is always false.
Loading history...
90 26
                return 0;
91
            }
92
            //error_log("real_connect($host, $user, $password, $database, $port)");
0 ignored issues
show
Unused Code Comprehensibility introduced by
80% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
93 26
            $this->linkId = mysqli_init();
94
            $this->linkId->options(MYSQLI_INIT_COMMAND, "SET NAMES {$this->characterSet} COLLATE {$this->collation}, COLLATION_CONNECTION = {$this->collation}, COLLATION_DATABASE = {$this->collation}");
95 26
            if (!$this->linkId->real_connect($host, $user, $password, $database, $port != '' ? $port : NULL)) {
96 26
                $this->halt("connect($host, $user, \$password) failed. ".(is_object($this->linkId) && isset( $this->linkId->connect_error) ? $this->linkId->connect_error : ''));
97
                return 0;
98
            }
99
            $this->linkId->set_charset($this->characterSet);
100
            if ($this->linkId->connect_errno) {
101 26
                $this->halt("connect($host, $user, \$password) failed. ".(is_object($this->linkId) && isset( $this->linkId->connect_error) ? $this->linkId->connect_error : ''));
102
                return 0;
103
            }
104
        }
105
        return $this->linkId;
106
    }
107
108 1
    /**
109
    * Db::disconnect()
110 1
    * @return bool
111 1
    */
112 1
    public function disconnect()
113
    {
114
        $return = !is_int($this->linkId) && method_exists($this->linkId, 'close') ? $this->linkId->close() : false;
115
        $this->linkId = 0;
116
        return $return;
117
    }
118
119 2
    /**
120
    * @param $string
121 2
    * @return string
122
    */
123
    public function real_escape($string = '')
124 2
    {
125
        if ((!is_resource($this->linkId) || $this->linkId == 0) && !$this->connect()) {
0 ignored issues
show
introduced by
The condition is_resource($this->linkId) is always false.
Loading history...
126
            return $this->escape($string);
127
        }
128
        return mysqli_real_escape_string($this->linkId, $string);
0 ignored issues
show
Bug introduced by
It seems like $this->linkId can also be of type integer and resource; however, parameter $mysql of mysqli_real_escape_string() does only seem to accept mysqli, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

128
        return mysqli_real_escape_string(/** @scrutinizer ignore-type */ $this->linkId, $string);
Loading history...
129
    }
130
131 1
    /**
132
    * discard the query result
133 1
    * @return void
134
    */
135
    public function free()
136 1
    {
137
        if (is_resource($this->queryId)) {
0 ignored issues
show
introduced by
The condition is_resource($this->queryId) is always false.
Loading history...
138
            @mysqli_free_result($this->queryId);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition for mysqli_free_result(). This can introduce security issues, and is generally not recommended. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unhandled  annotation

138
            /** @scrutinizer ignore-unhandled */ @mysqli_free_result($this->queryId);

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
139
        }
140
        $this->queryId = 0;
141
    }
142
143
    /**
144
    * Db::queryReturn()
145
    *
146
    * Sends an SQL query to the server like the normal query() command but iterates through
147
    * any rows and returns the row or rows immediately or FALSE on error
148
    *
149
    * @param mixed $query SQL Query to be used
150 1
    * @param string $line optionally pass __LINE__ calling the query for logging
151
    * @param string $file optionally pass __FILE__ calling the query for logging
152 1
    * @return mixed FALSE if no rows, if a single row it returns that, if multiple it returns an array of rows, associative responses only
153 1
    */
154 1
    public function queryReturn($query, $line = '', $file = '')
155 1
    {
156 1
        $this->query($query, $line, $file);
0 ignored issues
show
Bug introduced by
$line of type string is incompatible with the type integer expected by parameter $line of MyDb\Mysqli\Db::query(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

156
        $this->query($query, /** @scrutinizer ignore-type */ $line, $file);
Loading history...
157 1
        if ($this->num_rows() == 0) {
158
            return false;
159 1
        } elseif ($this->num_rows() == 1) {
160 1
            $this->next_record(MYSQLI_ASSOC);
161 1
            return $this->Record;
162
        } else {
163 1
            $out = [];
164
            while ($this->next_record(MYSQLI_ASSOC)) {
165
                $out[] = $this->Record;
166
            }
167
            return $out;
168
        }
169
    }
170
171
    /**
172
    * db:qr()
173
    *
174
    *  alias of queryReturn()
175
    *
176
    * @param mixed $query SQL Query to be used
177 1
    * @param string $line optionally pass __LINE__ calling the query for logging
178
    * @param string $file optionally pass __FILE__ calling the query for logging
179 1
    * @return mixed FALSE if no rows, if a single row it returns that, if multiple it returns an array of rows, associative responses only
180
    */
181
    public function qr($query, $line = '', $file = '')
182
    {
183
        return $this->queryReturn($query, $line, $file);
184
    }
185
186
    /**
187
    * creates a prepaired statement from query
188
    *
189
    * @param string $query sql query like INSERT INTO table (col) VALUES (?)  or  SELECT * from table WHERE col1 = ? and col2 = ?  or  UPDATE table SET col1 = ?, col2 = ? WHERE col3 = ?
190 1
    * @return false|mysqli_stmt
0 ignored issues
show
Bug introduced by
The type MyDb\Mysqli\mysqli_stmt was not found. Did you mean mysqli_stmt? If so, make sure to prefix the type with \.
Loading history...
191
    * @param string $line
192 1
    * @param string $file
193
    */
194
    public function prepare($query, $line = '', $file = '')
195 1
    {
196 1
        if (!$this->connect()) {
197 1
            return 0;
198 1
        }
199 1
        $haltPrev = $this->haltOnError;
0 ignored issues
show
Unused Code introduced by
The assignment to $haltPrev is dead and can be removed.
Loading history...
200 1
        $this->haltOnError = 'no';
201
        $start = microtime(true);
202
        $this->statement = mysqli_prepare($this->linkId, $query);
203
        if (!isset($GLOBALS['disable_db_queries'])) {
204
            $this->statement_query = $query;
205
            $this->addLog($query, microtime(true) - $start, $line, $file);
206
        }
207
        return $this->statement;
208
    }
209
210
    /**
211
    * Binds variables to a prepared statement as parameters
212
    * 
213 10
    * @param string $types A string that contains one or more characters which specify the types for the corresponding bind variables: (i)nt, (d)ecimal, (s)tring, (b)inary 
214
    * @param mixed $vars
215
    * @return bool indicates success
216
    */
217
    public function bind_param($types, &...$vars) {
218
        $params = [$this->statement, $types];
219
        foreach ($vars as &$var) {
220 10
            $params[] = &$var; // Ensure they stay references
221 1
        }
222
        $this->statement_vars &= $vars;
223 10
        return call_user_func_array('mysqli_stmt_bind_param', $params);
224
    }
225
226
    /**
227 10
    * Executes a prepared statement
228 10
    * 
229
    * @return bool success
230 10
    */
231
    public function execute($line = '', $file = '') {
232
        $start = microtime(true);
233 10
        $return = mysqli_stmt_execute($this->statement);
234 1
        if (!isset($GLOBALS['disable_db_queries'])) {
235
            $vars = $this->statement_vars;
236 10
            $query = $result = preg_replace_callback('/\?/', function () use (&$vars) {
0 ignored issues
show
Unused Code introduced by
The assignment to $result is dead and can be removed.
Loading history...
237
                return array_shift($vars);
238
                }, $this->statement_query);
239 10
            $this->addLog($query, microtime(true) - $start, $line, $file);
240 10
        }
241 10
        return $return;
242 10
    }
243 10
244 10
    /**
245
    * Db::query()
246
    *
247
    *  Sends an SQL query to the database
248 10
    *
249 10
    * @param mixed $queryString
250 10
    * @param int $line
251 10
    * @param string $file
252
    * @param bool $log
253
    * @return mixed 0 if no query or query id handler, safe to ignore this return
254
    */
255
    public function query($queryString, $line = '', $file = '', $log = false)
256
    {
257
        /* No empty queries, please, since PHP4 chokes on them. */
258 10
        /* The empty query string is passed on from the constructor,
259
        * when calling the class without a query, e.g. in situations
260
        * like these: '$db = new db_Subclass;'
261 10
        */
262 10
        if ($queryString == '') {
263 10
            return 0;
264 10
        }
265 10
        if (!$this->connect()) {
266
            return 0;
267
            /* we already complained in connect() about that. */
268
        }
269 10
        $haltPrev = $this->haltOnError;
270 10
        $this->haltOnError = 'no';
271
        // New query, discard previous result.
272
        if (is_resource($this->queryId)) {
273
            $this->free();
274
        }
275 10
        if ($this->Debug) {
276
            printf("Debug: query = %s<br>\n", $queryString);
277
        }
278
        if ($log === true || (isset($GLOBALS['log_queries']) && $GLOBALS['log_queries'] !== false)) {
279
            $this->log($queryString, $line, $file);
280
        }
281 1
        $tries = 2;
282
        $try = 0;
283 1
        $this->queryId = false;
284 1
        while ((null === $this->queryId || $this->queryId === false) && $try <= $tries) {
285
            $try++;
286
            if ($try > 1) {
287
                @mysqli_close($this->linkId);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition for mysqli_close(). This can introduce security issues, and is generally not recommended. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unhandled  annotation

287
                /** @scrutinizer ignore-unhandled */ @mysqli_close($this->linkId);

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
288
                $this->linkId = 0;
289
            }
290
            $start = microtime(true);
291
            $onlyRollback = true;
292
            $fails = -1;
293
            while ($fails < 30 && (null === $this->queryId || $this->queryId === false)) {
294
                $this->connect();
295 6
                $fails++;
296
                try {
297 6
                    $this->queryId = @mysqli_query($this->linkId, $queryString, MYSQLI_STORE_RESULT);
298
                    if (in_array((int)@mysqli_errno($this->linkId), [1213, 2006, 3101, 1180])) {
299
                        //error_log("got ".@mysqli_errno($this->linkId)." sql error fails {$fails} on query {$queryString} from {$line}:{$file}");
0 ignored issues
show
Unused Code Comprehensibility introduced by
67% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
300
                        usleep(250000); // 0.25 second
301
                    } else {
302 6
                        $onlyRollback = false;
303 6
                        if (in_array((int)@mysqli_errno($this->linkId), [1064])) {
304 6
                            $tries = 0;
305 6
                        }
306
                        break;
307 6
                    }
308 6
                } catch (\mysqli_sql_exception $e) {
309
                    if (in_array((int)$e->getCode(), [1213, 2006, 3101, 1180])) {
310
                        //error_log("got ".$e->getCode()." sql error fails {$fails}");
0 ignored issues
show
Unused Code Comprehensibility introduced by
70% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
311 6
                        usleep(250000); // 0.25 second
312
                    } else {
313
                        error_log('Got mysqli_sql_exception code '.$e->getCode().' error '.$e->getMessage().' on query '.$queryString.' from '.$line.':'.$file);
314
                        $onlyRollback = false;
315
                        if (in_array((int)@mysqli_errno($this->linkId), [1064])) {
316
                            $tries = 0;
317
                        }
318
                        break;
319
                    }
320 1
                }
321
            }
322 1
            if (!isset($GLOBALS['disable_db_queries'])) {
323 1
                $this->addLog($queryString, microtime(true) - $start, $line, $file);
324 1
            }
325
            $this->Row = 0;
326 1
            $this->Errno = @mysqli_errno($this->linkId);
327
            $this->Error = @mysqli_error($this->linkId);
328 1
            if ($try == 1 && (null === $this->queryId || $this->queryId === false)) {
0 ignored issues
show
Unused Code introduced by
This if statement is empty and can be removed.

This check looks for the bodies of if statements that have no statements or where all statements have been commented out. This may be the result of changes for debugging or the code may simply be obsolete.

These if bodies can be removed. If you have an empty if but statements in the else branch, consider inverting the condition.

if (rand(1, 6) > 3) {
//print "Check failed";
} else {
    print "Check succeeded";
}

could be turned into

if (rand(1, 6) <= 3) {
    print "Check succeeded";
}

This is much more concise to read.

Loading history...
329 1
                //$this->emailError($queryString, 'Error #'.$this->Errno.': '.$this->Error, $line, $file);
0 ignored issues
show
Unused Code Comprehensibility introduced by
66% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
330 1
            }
331 1
        }
332
        $this->haltOnError = $haltPrev;
333 1
        if ($onlyRollback === true && false === $this->queryId) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $onlyRollback does not seem to be defined for all execution paths leading up to this point.
Loading history...
334
            error_log('Got MySQLi 3101 Rollback Error '.$fails.' Times, Giving Up on '.$queryString.' from '.$line.':'.$file.' on '.__LINE__.':'.__FILE__);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $fails does not seem to be defined for all execution paths leading up to this point.
Loading history...
335
        }
336
        if (null === $this->queryId || $this->queryId === false) {
337
            $this->emailError($queryString, 'Error #'.$this->Errno.': '.$this->Error, $line, $file);
338
            $this->halt('', $line, $file);
339
        }
340
341 26
        // Will return nada if it fails. That's fine.
342
        return $this->queryId;
343 26
    }
344
345
    /**
346 26
    * @return array|null|object
347
    */
348
    public function fetchObject()
349 26
    {
350
        $this->Record = @mysqli_fetch_object($this->queryId);
0 ignored issues
show
Bug introduced by
$this->queryId of type integer is incompatible with the type mysqli_result expected by parameter $result of mysqli_fetch_object(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

350
        $this->Record = @mysqli_fetch_object(/** @scrutinizer ignore-type */ $this->queryId);
Loading history...
351
        return $this->Record;
352
    }
353
354
    /* public: walk result set */
355
356
    /**
357 1
    * Db::next_record()
358
    *
359 1
    * @param mixed $resultType
360
    * @return bool
361
    */
362 1
    public function next_record($resultType = MYSQLI_BOTH)
363
    {
364
        if ($this->queryId === false) {
0 ignored issues
show
introduced by
The condition $this->queryId === false is always false.
Loading history...
365
            $this->haltmsg('next_record called with no query pending.');
366
            return 0;
367
        }
368
369
        $this->Record = @mysqli_fetch_array($this->queryId, $resultType);
0 ignored issues
show
Bug introduced by
$this->queryId of type integer is incompatible with the type mysqli_result expected by parameter $result of mysqli_fetch_array(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

369
        $this->Record = @mysqli_fetch_array(/** @scrutinizer ignore-type */ $this->queryId, $resultType);
Loading history...
370 26
        ++$this->Row;
371
        $this->Errno = mysqli_errno($this->linkId);
0 ignored issues
show
Bug introduced by
It seems like $this->linkId can also be of type integer; however, parameter $mysql of mysqli_errno() does only seem to accept mysqli, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

371
        $this->Errno = mysqli_errno(/** @scrutinizer ignore-type */ $this->linkId);
Loading history...
372 26
        $this->Error = mysqli_error($this->linkId);
0 ignored issues
show
Bug introduced by
It seems like $this->linkId can also be of type integer; however, parameter $mysql of mysqli_error() does only seem to accept mysqli, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

372
        $this->Error = mysqli_error(/** @scrutinizer ignore-type */ $this->linkId);
Loading history...
373
374
        $stat = is_array($this->Record);
375 26
        if (!$stat && $this->autoFree && is_resource($this->queryId)) {
0 ignored issues
show
introduced by
The condition is_resource($this->queryId) is always false.
Loading history...
376
            $this->free();
377
        }
378
        return $stat;
379
    }
380
381
    /**
382
    * switch to position in result set
383
    *
384
    * @param integer $pos the row numbe starting at 0 to switch to
385
    * @return bool whetherit was successfu or not.
386
    */
387 2
    public function seek($pos = 0)
388
    {
389 2
        $status = @mysqli_data_seek($this->queryId, $pos);
0 ignored issues
show
Bug introduced by
$this->queryId of type integer is incompatible with the type mysqli_result expected by parameter $result of mysqli_data_seek(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

389
        $status = @mysqli_data_seek(/** @scrutinizer ignore-type */ $this->queryId, $pos);
Loading history...
390
        if ($status) {
391
            $this->Row = $pos;
392
        } else {
393 2
            $this->haltmsg("seek({$pos}) failed: result has ".$this->num_rows().' rows', __LINE__, __FILE__);
394
            /* half assed attempt to save the day, but do not consider this documented or even desirable behaviour. */
395
            $rows = $this->num_rows();
396
            @mysqli_data_seek($this->queryId, $rows);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition for mysqli_data_seek(). This can introduce security issues, and is generally not recommended. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unhandled  annotation

396
            /** @scrutinizer ignore-unhandled */ @mysqli_data_seek($this->queryId, $rows);

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
397
            $this->Row = $rows;
398
            return false;
399
        }
400
        return true;
401
    }
402
403
    /**
404 1
    * Initiates a transaction
405
    *
406 1
    * @return bool
407 1
    */
408 1
    public function transactionBegin()
409 1
    {
410 1
        if (version_compare(PHP_VERSION, '5.5.0') < 0) {
411
            return true;
412
        }
413 1
        if (!$this->connect()) {
414
            return 0;
415
        }
416 1
        return mysqli_begin_transaction($this->linkId);
417
    }
418 1
419
    /**
420 1
    * Commits a transaction
421 1
    *
422
    * @return bool
423
    */
424
    public function transactionCommit()
425 1
    {
426
        if (version_compare(PHP_VERSION, '5.5.0') < 0 || $this->linkId === 0) {
427
            return true;
428
        }
429
        return mysqli_commit($this->linkId);
0 ignored issues
show
Bug introduced by
It seems like $this->linkId can also be of type integer; however, parameter $mysql of mysqli_commit() does only seem to accept mysqli, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

429
        return mysqli_commit(/** @scrutinizer ignore-type */ $this->linkId);
Loading history...
430
    }
431
432
    /**
433 2
    * Rolls back a transaction
434
    *
435 2
    * @return bool
436
    */
437 2
    public function transactionAbort()
438 2
    {
439
        if (version_compare(PHP_VERSION, '5.5.0') < 0 || $this->linkId === 0) {
440
            return true;
441
        }
442 2
        return mysqli_rollback($this->linkId);
0 ignored issues
show
Bug introduced by
It seems like $this->linkId can also be of type integer; however, parameter $mysql of mysqli_rollback() does only seem to accept mysqli, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

442
        return mysqli_rollback(/** @scrutinizer ignore-type */ $this->linkId);
Loading history...
443
    }
444
445
    /**
446
    * This will get the last insert ID created on the current connection.  Should only be called after an insert query is
447
    * run on a table that has an auto incrementing field.  $table and $field are required, but unused here since it's
448
    * unnecessary for mysql.  For compatibility with pgsql, the params must be supplied.
449
    *
450
    * @param string $table
451 2
    * @param string $field
452
    * @return int|string
453 2
    */
454
    public function getLastInsertId($table, $field)
455
    {
456
        if (!isset($table) || $table == '' || !isset($field) || $field == '') {
457
            return -1;
458
        }
459
460 6
        return @mysqli_insert_id($this->linkId);
0 ignored issues
show
Bug introduced by
It seems like $this->linkId can also be of type integer; however, parameter $mysql of mysqli_insert_id() does only seem to accept mysqli, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

460
        return @mysqli_insert_id(/** @scrutinizer ignore-type */ $this->linkId);
Loading history...
461
    }
462 6
463
    /* public: table locking */
464
465
    /**
466
    * Db::lock()
467
    * @param mixed  $table
468
    * @param string $mode
469 1
    * @return bool|int|\mysqli_result
470
    */
471 1
    public function lock($table, $mode = 'write')
472
    {
473
        $this->connect();
474
        $query = 'lock tables ';
475
        if (is_array($table)) {
476
            foreach ($table as $key => $value) {
477
                if ($key == 'read' && $key != 0) {
478
                    $query .= "$value read, ";
479 1
                } else {
480
                    $query .= "$value $mode, ";
481 1
                }
482 1
            }
483 1
            $query = mb_substr($query, 0, -2);
484 1
        } else {
485 1
            $query .= "$table $mode";
486 1
        }
487 1
        $res = @mysqli_query($this->linkId, $query);
488 1
        if (!$res) {
489
            $this->halt("lock($table, $mode) failed.");
490 1
            return 0;
491
        }
492
        return $res;
493
    }
494
495
    /**
496
    * Db::unlock()
497
    * @param bool $haltOnError optional, defaults to TRUE, whether or not to halt on error
498
    * @return bool|int|\mysqli_result
499
    */
500
    public function unlock($haltOnError = true)
501
    {
502
        $this->connect();
503
504
        $res = @mysqli_query($this->linkId, 'unlock tables');
505
        if ($haltOnError === true && !$res) {
506
            $this->halt('unlock() failed.');
507
            return 0;
508
        }
509
        return $res;
510
    }
511
512
    /* public: evaluate the result (size, width) */
513
514
    /**
515
    * Db::affectedRows()
516
    * @return int
517
    */
518
    public function affectedRows()
519
    {
520
        return @mysqli_affected_rows($this->linkId);
0 ignored issues
show
Bug introduced by
It seems like $this->linkId can also be of type integer; however, parameter $mysql of mysqli_affected_rows() does only seem to accept mysqli, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

520
        return @mysqli_affected_rows(/** @scrutinizer ignore-type */ $this->linkId);
Loading history...
521
    }
522
523
    /**
524
    * Db::num_rows()
525
    * @return int
526
    */
527
    public function num_rows()
528
    {
529
        return @mysqli_num_rows($this->queryId);
0 ignored issues
show
Bug introduced by
$this->queryId of type integer is incompatible with the type mysqli_result expected by parameter $result of mysqli_num_rows(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

529
        return @mysqli_num_rows(/** @scrutinizer ignore-type */ $this->queryId);
Loading history...
530
    }
531
532
    /**
533
    * Db::num_fields()
534
    * @return int
535
    */
536
    public function num_fields()
537
    {
538
        return @mysqli_num_fields($this->queryId);
0 ignored issues
show
Bug introduced by
$this->queryId of type integer is incompatible with the type mysqli_result expected by parameter $result of mysqli_num_fields(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

538
        return @mysqli_num_fields(/** @scrutinizer ignore-type */ $this->queryId);
Loading history...
539
    }
540
541
    /**
542
    * gets an array of the table names in teh current datase
543
    *
544
    * @return array
545
    */
546
    public function tableNames()
547
    {
548
        $return = [];
549
        $this->query('SHOW TABLES');
550
        $i = 0;
551
        while ($info = $this->queryId->fetch_row()) {
0 ignored issues
show
Bug introduced by
The method fetch_row() does not exist on integer. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

551
        while ($info = $this->queryId->/** @scrutinizer ignore-call */ fetch_row()) {

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
552
            $return[$i]['table_name'] = $info[0];
553
            $return[$i]['tablespace_name'] = $this->database;
554
            $return[$i]['database'] = $this->database;
555
            ++$i;
556
        }
557
        return $return;
558
    }
559
}
560
561
/**
562
* @param $result
563
* @param $row
564
* @param int|string $field
565
* @return bool
566
*/
567
/*
0 ignored issues
show
Unused Code Comprehensibility introduced by
56% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
568
function mysqli_result($result, $row, $field = 0) {
569
if ($result === false) return false;
570
if ($row >= mysqli_num_rows($result)) return false;
571
if (is_string($field) && !(mb_strpos($field, '.') === false)) {
572
$tField = explode('.', $field);
573
$field = -1;
574
$tFields = mysqli_fetch_fields($result);
575
for ($id = 0, $idMax = mysqli_num_fields($result); $id < $idMax; $id++) {
576
if ($tFields[$id]->table == $tField[0] && $tFields[$id]->name == $tField[1]) {
577
$field = $id;
578
break;
579
}
580
}
581
if ($field == -1) return false;
582
}
583
mysqli_data_seek($result, $row);
584
$line = mysqli_fetch_array($result);
585
return isset($line[$field]) ? $line[$field] : false;
586
}
587
*/
588