Test Failed
Push — master ( 22f89e...9a50d4 )
by Joe
15:33 queued 12:00
created
src/Mysqli/Db.php 1 patch
Indentation   +480 added lines, -480 removed lines patch added patch discarded remove patch
@@ -19,489 +19,489 @@
 block discarded – undo
19 19
  */
20 20
 class Db extends Generic implements Db_Interface
21 21
 {
22
-    /**
23
-     * @var string
24
-     */
25
-    public $type = 'mysqli';
26
-
27
-    /**
28
-     * alias function of select_db, changes the database we are working with.
29
-     *
30
-     * @param string $database the name of the database to use
31
-     * @return void
32
-     */
33
-    public function useDb($database)
34
-    {
35
-        $this->selectDb($database);
36
-    }
37
-
38
-    /**
39
-     * changes the database we are working with.
40
-     *
41
-     * @param string $database the name of the database to use
42
-     * @return void
43
-     */
44
-    public function selectDb($database)
45
-    {
46
-        $this->connect();
47
-        mysqli_select_db($this->linkId, $database);
48
-    }
49
-
50
-    /* public: connection management */
51
-
52
-    /**
53
-     * Db::connect()
54
-     * @param string $database
55
-     * @param string $host
56
-     * @param string $user
57
-     * @param string $password
58
-     * @return int|\mysqli
59
-     */
60
-    public function connect($database = '', $host = '', $user = '', $password = '', $port = '')
61
-    {
62
-        /* Handle defaults */
63
-        if ($database == '') {
64
-            $database = $this->database;
65
-        }
66
-        if ($host == '') {
67
-            $host = $this->host;
68
-        }
69
-        if ($user == '') {
70
-            $user = $this->user;
71
-        }
72
-        if ($password == '') {
73
-            $password = $this->password;
74
-        }
75
-        if ($port == '') {
76
-            $port = $this->port;
77
-        }
78
-        /* establish connection, select database */
79
-        if (!is_object($this->linkId)) {
80
-            $this->connectionAttempt++;
81
-            if ($this->connectionAttempt > 1) {
82
-                error_log("MySQLi Connection Attempt #{$this->connectionAttempt}/{$this->maxConnectErrors}");
83
-            }
84
-            if ($this->connectionAttempt >= $this->maxConnectErrors) {
85
-                $this->halt("connect($host, $user, \$password) failed. ".$mysqli->connect_error);
86
-                return 0;
87
-            }
88
-            $this->linkId = mysqli_init();
89
-            $this->linkId->options(MYSQLI_INIT_COMMAND, "SET NAMES {$this->characterSet} COLLATE {$this->collation}, COLLATION_CONNECTION = {$this->collation}, COLLATION_DATABASE = {$this->collation}");
90
-            if ($port != '') {
91
-                $this->linkId->real_connect($host, $user, $password, $database, $port);
92
-            } else {
93
-                $this->linkId->real_connect($host, $user, $password, $database);
94
-            }
95
-            $this->linkId->set_charset($this->characterSet);
96
-            if ($this->linkId->connect_errno) {
97
-                $this->halt("connect($host, $user, \$password) failed. ".$mysqli->connect_error);
98
-                return 0;
99
-            }
100
-        }
101
-        return $this->linkId;
102
-    }
103
-
104
-    /**
105
-     * Db::disconnect()
106
-     * @return bool
107
-     */
108
-    public function disconnect()
109
-    {
110
-        $return = !is_int($this->linkId) && method_exists($this->linkId, 'close') ? $this->linkId->close() : false;
111
-        $this->linkId = 0;
112
-        return $return;
113
-    }
114
-
115
-    /**
116
-     * @param $string
117
-     * @return string
118
-     */
119
-    public function real_escape($string = '')
120
-    {
121
-        if ((!is_resource($this->linkId) || $this->linkId == 0) && !$this->connect()) {
122
-            return $this->escape($string);
123
-        }
124
-        return mysqli_real_escape_string($this->linkId, $string);
125
-    }
126
-
127
-    /**
128
-     * discard the query result
129
-     * @return void
130
-     */
131
-    public function free()
132
-    {
133
-        if (is_resource($this->queryId)) {
134
-            @mysqli_free_result($this->queryId);
135
-        }
136
-        $this->queryId = 0;
137
-    }
138
-
139
-    /**
140
-     * Db::queryReturn()
141
-     *
142
-     * Sends an SQL query to the server like the normal query() command but iterates through
143
-     * any rows and returns the row or rows immediately or FALSE on error
144
-     *
145
-     * @param mixed $query SQL Query to be used
146
-     * @param string $line optionally pass __LINE__ calling the query for logging
147
-     * @param string $file optionally pass __FILE__ calling the query for logging
148
-     * @return mixed FALSE if no rows, if a single row it returns that, if multiple it returns an array of rows, associative responses only
149
-     */
150
-    public function queryReturn($query, $line = '', $file = '')
151
-    {
152
-        $this->query($query, $line, $file);
153
-        if ($this->num_rows() == 0) {
154
-            return false;
155
-        } elseif ($this->num_rows() == 1) {
156
-            $this->next_record(MYSQLI_ASSOC);
157
-            return $this->Record;
158
-        } else {
159
-            $out = [];
160
-            while ($this->next_record(MYSQLI_ASSOC)) {
161
-                $out[] = $this->Record;
162
-            }
163
-            return $out;
164
-        }
165
-    }
166
-
167
-    /**
168
-     * db:qr()
169
-     *
170
-     *  alias of queryReturn()
171
-     *
172
-     * @param mixed $query SQL Query to be used
173
-     * @param string $line optionally pass __LINE__ calling the query for logging
174
-     * @param string $file optionally pass __FILE__ calling the query for logging
175
-     * @return mixed FALSE if no rows, if a single row it returns that, if multiple it returns an array of rows, associative responses only
176
-     */
177
-    public function qr($query, $line = '', $file = '')
178
-    {
179
-        return $this->queryReturn($query, $line, $file);
180
-    }
181
-
182
-    /**
183
-     * creates a prepaired statement from query
184
-     *
185
-     * @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 = ?
186
-     * @return int|\MyDb\Mysqli\mysqli_stmt
187
-     * @param string $line
188
-     * @param string $file
189
-     */
190
-    public function prepare($query, $line = '', $file = '')
191
-    {
192
-        if (!$this->connect()) {
193
-            return 0;
194
-        }
195
-        $haltPrev = $this->haltOnError;
196
-        $this->haltOnError = 'no';
197
-        $start = microtime(true);
198
-        $prepare = mysqli_prepare($this->linkId, $query);
199
-        $this->addLog($query, microtime(true) - $start, $line, $file);
200
-        return $prepare;
201
-    }
202
-
203
-    /**
204
-     * Db::query()
205
-     *
206
-     *  Sends an SQL query to the database
207
-     *
208
-     * @param mixed $queryString
209
-     * @param string $line
210
-     * @param string $file
211
-     * @return mixed 0 if no query or query id handler, safe to ignore this return
212
-     */
213
-    public function query($queryString, $line = '', $file = '')
214
-    {
215
-        /* No empty queries, please, since PHP4 chokes on them. */
216
-        /* The empty query string is passed on from the constructor,
22
+	/**
23
+	 * @var string
24
+	 */
25
+	public $type = 'mysqli';
26
+
27
+	/**
28
+	 * alias function of select_db, changes the database we are working with.
29
+	 *
30
+	 * @param string $database the name of the database to use
31
+	 * @return void
32
+	 */
33
+	public function useDb($database)
34
+	{
35
+		$this->selectDb($database);
36
+	}
37
+
38
+	/**
39
+	 * changes the database we are working with.
40
+	 *
41
+	 * @param string $database the name of the database to use
42
+	 * @return void
43
+	 */
44
+	public function selectDb($database)
45
+	{
46
+		$this->connect();
47
+		mysqli_select_db($this->linkId, $database);
48
+	}
49
+
50
+	/* public: connection management */
51
+
52
+	/**
53
+	 * Db::connect()
54
+	 * @param string $database
55
+	 * @param string $host
56
+	 * @param string $user
57
+	 * @param string $password
58
+	 * @return int|\mysqli
59
+	 */
60
+	public function connect($database = '', $host = '', $user = '', $password = '', $port = '')
61
+	{
62
+		/* Handle defaults */
63
+		if ($database == '') {
64
+			$database = $this->database;
65
+		}
66
+		if ($host == '') {
67
+			$host = $this->host;
68
+		}
69
+		if ($user == '') {
70
+			$user = $this->user;
71
+		}
72
+		if ($password == '') {
73
+			$password = $this->password;
74
+		}
75
+		if ($port == '') {
76
+			$port = $this->port;
77
+		}
78
+		/* establish connection, select database */
79
+		if (!is_object($this->linkId)) {
80
+			$this->connectionAttempt++;
81
+			if ($this->connectionAttempt > 1) {
82
+				error_log("MySQLi Connection Attempt #{$this->connectionAttempt}/{$this->maxConnectErrors}");
83
+			}
84
+			if ($this->connectionAttempt >= $this->maxConnectErrors) {
85
+				$this->halt("connect($host, $user, \$password) failed. ".$mysqli->connect_error);
86
+				return 0;
87
+			}
88
+			$this->linkId = mysqli_init();
89
+			$this->linkId->options(MYSQLI_INIT_COMMAND, "SET NAMES {$this->characterSet} COLLATE {$this->collation}, COLLATION_CONNECTION = {$this->collation}, COLLATION_DATABASE = {$this->collation}");
90
+			if ($port != '') {
91
+				$this->linkId->real_connect($host, $user, $password, $database, $port);
92
+			} else {
93
+				$this->linkId->real_connect($host, $user, $password, $database);
94
+			}
95
+			$this->linkId->set_charset($this->characterSet);
96
+			if ($this->linkId->connect_errno) {
97
+				$this->halt("connect($host, $user, \$password) failed. ".$mysqli->connect_error);
98
+				return 0;
99
+			}
100
+		}
101
+		return $this->linkId;
102
+	}
103
+
104
+	/**
105
+	 * Db::disconnect()
106
+	 * @return bool
107
+	 */
108
+	public function disconnect()
109
+	{
110
+		$return = !is_int($this->linkId) && method_exists($this->linkId, 'close') ? $this->linkId->close() : false;
111
+		$this->linkId = 0;
112
+		return $return;
113
+	}
114
+
115
+	/**
116
+	 * @param $string
117
+	 * @return string
118
+	 */
119
+	public function real_escape($string = '')
120
+	{
121
+		if ((!is_resource($this->linkId) || $this->linkId == 0) && !$this->connect()) {
122
+			return $this->escape($string);
123
+		}
124
+		return mysqli_real_escape_string($this->linkId, $string);
125
+	}
126
+
127
+	/**
128
+	 * discard the query result
129
+	 * @return void
130
+	 */
131
+	public function free()
132
+	{
133
+		if (is_resource($this->queryId)) {
134
+			@mysqli_free_result($this->queryId);
135
+		}
136
+		$this->queryId = 0;
137
+	}
138
+
139
+	/**
140
+	 * Db::queryReturn()
141
+	 *
142
+	 * Sends an SQL query to the server like the normal query() command but iterates through
143
+	 * any rows and returns the row or rows immediately or FALSE on error
144
+	 *
145
+	 * @param mixed $query SQL Query to be used
146
+	 * @param string $line optionally pass __LINE__ calling the query for logging
147
+	 * @param string $file optionally pass __FILE__ calling the query for logging
148
+	 * @return mixed FALSE if no rows, if a single row it returns that, if multiple it returns an array of rows, associative responses only
149
+	 */
150
+	public function queryReturn($query, $line = '', $file = '')
151
+	{
152
+		$this->query($query, $line, $file);
153
+		if ($this->num_rows() == 0) {
154
+			return false;
155
+		} elseif ($this->num_rows() == 1) {
156
+			$this->next_record(MYSQLI_ASSOC);
157
+			return $this->Record;
158
+		} else {
159
+			$out = [];
160
+			while ($this->next_record(MYSQLI_ASSOC)) {
161
+				$out[] = $this->Record;
162
+			}
163
+			return $out;
164
+		}
165
+	}
166
+
167
+	/**
168
+	 * db:qr()
169
+	 *
170
+	 *  alias of queryReturn()
171
+	 *
172
+	 * @param mixed $query SQL Query to be used
173
+	 * @param string $line optionally pass __LINE__ calling the query for logging
174
+	 * @param string $file optionally pass __FILE__ calling the query for logging
175
+	 * @return mixed FALSE if no rows, if a single row it returns that, if multiple it returns an array of rows, associative responses only
176
+	 */
177
+	public function qr($query, $line = '', $file = '')
178
+	{
179
+		return $this->queryReturn($query, $line, $file);
180
+	}
181
+
182
+	/**
183
+	 * creates a prepaired statement from query
184
+	 *
185
+	 * @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 = ?
186
+	 * @return int|\MyDb\Mysqli\mysqli_stmt
187
+	 * @param string $line
188
+	 * @param string $file
189
+	 */
190
+	public function prepare($query, $line = '', $file = '')
191
+	{
192
+		if (!$this->connect()) {
193
+			return 0;
194
+		}
195
+		$haltPrev = $this->haltOnError;
196
+		$this->haltOnError = 'no';
197
+		$start = microtime(true);
198
+		$prepare = mysqli_prepare($this->linkId, $query);
199
+		$this->addLog($query, microtime(true) - $start, $line, $file);
200
+		return $prepare;
201
+	}
202
+
203
+	/**
204
+	 * Db::query()
205
+	 *
206
+	 *  Sends an SQL query to the database
207
+	 *
208
+	 * @param mixed $queryString
209
+	 * @param string $line
210
+	 * @param string $file
211
+	 * @return mixed 0 if no query or query id handler, safe to ignore this return
212
+	 */
213
+	public function query($queryString, $line = '', $file = '')
214
+	{
215
+		/* No empty queries, please, since PHP4 chokes on them. */
216
+		/* The empty query string is passed on from the constructor,
217 217
         * when calling the class without a query, e.g. in situations
218 218
         * like these: '$db = new db_Subclass;'
219 219
         */
220
-        if ($queryString == '') {
221
-            return 0;
222
-        }
223
-        if (!$this->connect()) {
224
-            return 0;
225
-            /* we already complained in connect() about that. */
226
-        }
227
-        $haltPrev = $this->haltOnError;
228
-        $this->haltOnError = 'no';
229
-        // New query, discard previous result.
230
-        if (is_resource($this->queryId)) {
231
-            $this->free();
232
-        }
233
-        if ($this->Debug) {
234
-            printf("Debug: query = %s<br>\n", $queryString);
235
-        }
236
-        if (isset($GLOBALS['log_queries']) && $GLOBALS['log_queries'] !== false) {
237
-            $this->log($queryString, $line, $file);
238
-        }
239
-        $tries = 3;
240
-        $try = 0;
241
-        $this->queryId = false;
242
-        while ((null === $this->queryId || $this->queryId === false) && $try <= $tries) {
243
-            $try++;
244
-            if ($try > 1) {
245
-                @mysqli_close($this->linkId);
246
-                $this->connect();
247
-            }
248
-            $start = microtime(true);
249
-            $onlyRollback = true;
250
-            $fails = -1;
251
-            while ($fails < 100 && (null === $this->queryId || $this->queryId === false)) {
252
-                $fails++;
253
-                try {
254
-                    $this->queryId = @mysqli_query($this->linkId, $queryString, MYSQLI_STORE_RESULT);
255
-                    if (in_array(@mysqli_errno($this->linkId), [2006, 3101, 1180])) {
256
-                        //error_log("got ".@mysqli_errno($this->linkId)." sql error fails {$fails} on query {$queryString} from {$line}:{$file}");
257
-                        usleep(500000); // 0.5 second
258
-                    } else {
259
-                        $onlyRollback = false;
260
-                    }
261
-                } catch (\mysqli_sql_exception $e) {
262
-                    if (in_array($e->getCode(), [2006, 3101, 1180])) {
263
-                        //error_log("got ".$e->getCode()." sql error fails {$fails}");
264
-                        usleep(500000); // 0.5 second
265
-                    } else {
266
-                        error_log('Got mysqli_sql_exception code '.$e->getCode().' error '.$e->getMessage().' on query '.$queryString.' from '.$line.':'.$file);
267
-                        $onlyRollback = false;
268
-                    }
269
-                }
270
-            }
271
-            if ($onlyRollback === true && false === $this->queryId) {
272
-                error_log('Got MySQLi 3101 Rollback Error '.$fails.' Times, Giving Up on '.$queryString.' from '.$line.':'.$file.' on '.__LINE__.':'.__FILE__);
273
-            }
274
-            $this->addLog($queryString, microtime(true) - $start, $line, $file);
275
-            $this->Row = 0;
276
-            $this->Errno = @mysqli_errno($this->linkId);
277
-            $this->Error = @mysqli_error($this->linkId);
278
-            if ($try == 1 && (null === $this->queryId || $this->queryId === false)) {
279
-                $this->emailError($queryString, 'Error #'.$this->Errno.': '.$this->Error, $line, $file);
280
-            }
281
-        }
282
-        $this->haltOnError = $haltPrev;
283
-        if (null === $this->queryId || $this->queryId === false) {
284
-            $this->halt('', $line, $file);
285
-        }
286
-
287
-        // Will return nada if it fails. That's fine.
288
-        return $this->queryId;
289
-    }
290
-
291
-    /**
292
-     * @return array|null|object
293
-     */
294
-    public function fetchObject()
295
-    {
296
-        $this->Record = @mysqli_fetch_object($this->queryId);
297
-        return $this->Record;
298
-    }
299
-
300
-    /* public: walk result set */
301
-
302
-    /**
303
-     * Db::next_record()
304
-     *
305
-     * @param mixed $resultType
306
-     * @return bool
307
-     */
308
-    public function next_record($resultType = MYSQLI_BOTH)
309
-    {
310
-        if ($this->queryId === false) {
311
-            $this->haltmsg('next_record called with no query pending.');
312
-            return 0;
313
-        }
314
-
315
-        $this->Record = @mysqli_fetch_array($this->queryId, $resultType);
316
-        ++$this->Row;
317
-        $this->Errno = mysqli_errno($this->linkId);
318
-        $this->Error = mysqli_error($this->linkId);
319
-
320
-        $stat = is_array($this->Record);
321
-        if (!$stat && $this->autoFree && is_resource($this->queryId)) {
322
-            $this->free();
323
-        }
324
-        return $stat;
325
-    }
326
-
327
-    /**
328
-     * switch to position in result set
329
-     *
330
-     * @param integer $pos the row numbe starting at 0 to switch to
331
-     * @return bool whetherit was successfu or not.
332
-     */
333
-    public function seek($pos = 0)
334
-    {
335
-        $status = @mysqli_data_seek($this->queryId, $pos);
336
-        if ($status) {
337
-            $this->Row = $pos;
338
-        } else {
339
-            $this->haltmsg("seek({$pos}) failed: result has ".$this->num_rows().' rows', __LINE__, __FILE__);
340
-            /* half assed attempt to save the day, but do not consider this documented or even desirable behaviour. */
341
-            $rows = $this->num_rows();
342
-            @mysqli_data_seek($this->queryId, $rows);
343
-            $this->Row = $rows;
344
-            return false;
345
-        }
346
-        return true;
347
-    }
348
-
349
-    /**
350
-     * Initiates a transaction
351
-     *
352
-     * @return bool
353
-     */
354
-    public function transactionBegin()
355
-    {
356
-        if (version_compare(PHP_VERSION, '5.5.0') < 0) {
357
-            return true;
358
-        }
359
-        if (!$this->connect()) {
360
-            return 0;
361
-        }
362
-        return mysqli_begin_transaction($this->linkId);
363
-    }
364
-
365
-    /**
366
-     * Commits a transaction
367
-     *
368
-     * @return bool
369
-     */
370
-    public function transactionCommit()
371
-    {
372
-        if (version_compare(PHP_VERSION, '5.5.0') < 0 || $this->linkId === 0) {
373
-            return true;
374
-        }
375
-        return mysqli_commit($this->linkId);
376
-    }
377
-
378
-    /**
379
-     * Rolls back a transaction
380
-     *
381
-     * @return bool
382
-     */
383
-    public function transactionAbort()
384
-    {
385
-        if (version_compare(PHP_VERSION, '5.5.0') < 0 || $this->linkId === 0) {
386
-            return true;
387
-        }
388
-        return mysqli_rollback($this->linkId);
389
-    }
390
-
391
-    /**
392
-     * This will get the last insert ID created on the current connection.  Should only be called after an insert query is
393
-     * run on a table that has an auto incrementing field.  $table and $field are required, but unused here since it's
394
-     * unnecessary for mysql.  For compatibility with pgsql, the params must be supplied.
395
-     *
396
-     * @param string $table
397
-     * @param string $field
398
-     * @return int|string
399
-     */
400
-    public function getLastInsertId($table, $field)
401
-    {
402
-        if (!isset($table) || $table == '' || !isset($field) || $field == '') {
403
-            return -1;
404
-        }
405
-
406
-        return @mysqli_insert_id($this->linkId);
407
-    }
408
-
409
-    /* public: table locking */
410
-
411
-    /**
412
-     * Db::lock()
413
-     * @param mixed  $table
414
-     * @param string $mode
415
-     * @return bool|int|\mysqli_result
416
-     */
417
-    public function lock($table, $mode = 'write')
418
-    {
419
-        $this->connect();
420
-        $query = 'lock tables ';
421
-        if (is_array($table)) {
422
-            foreach ($table as $key => $value) {
423
-                if ($key == 'read' && $key != 0) {
424
-                    $query .= "$value read, ";
425
-                } else {
426
-                    $query .= "$value $mode, ";
427
-                }
428
-            }
429
-            $query = mb_substr($query, 0, -2);
430
-        } else {
431
-            $query .= "$table $mode";
432
-        }
433
-        $res = @mysqli_query($this->linkId, $query);
434
-        if (!$res) {
435
-            $this->halt("lock($table, $mode) failed.");
436
-            return 0;
437
-        }
438
-        return $res;
439
-    }
440
-
441
-    /**
442
-     * Db::unlock()
443
-     * @param bool $haltOnError optional, defaults to TRUE, whether or not to halt on error
444
-     * @return bool|int|\mysqli_result
445
-     */
446
-    public function unlock($haltOnError = true)
447
-    {
448
-        $this->connect();
449
-
450
-        $res = @mysqli_query($this->linkId, 'unlock tables');
451
-        if ($haltOnError === true && !$res) {
452
-            $this->halt('unlock() failed.');
453
-            return 0;
454
-        }
455
-        return $res;
456
-    }
457
-
458
-    /* public: evaluate the result (size, width) */
459
-
460
-    /**
461
-     * Db::affectedRows()
462
-     * @return int
463
-     */
464
-    public function affectedRows()
465
-    {
466
-        return @mysqli_affected_rows($this->linkId);
467
-    }
468
-
469
-    /**
470
-     * Db::num_rows()
471
-     * @return int
472
-     */
473
-    public function num_rows()
474
-    {
475
-        return @mysqli_num_rows($this->queryId);
476
-    }
477
-
478
-    /**
479
-     * Db::num_fields()
480
-     * @return int
481
-     */
482
-    public function num_fields()
483
-    {
484
-        return @mysqli_num_fields($this->queryId);
485
-    }
486
-
487
-    /**
488
-     * gets an array of the table names in teh current datase
489
-     *
490
-     * @return array
491
-     */
492
-    public function tableNames()
493
-    {
494
-        $return = [];
495
-        $this->query('SHOW TABLES');
496
-        $i = 0;
497
-        while ($info = $this->queryId->fetch_row()) {
498
-            $return[$i]['table_name'] = $info[0];
499
-            $return[$i]['tablespace_name'] = $this->database;
500
-            $return[$i]['database'] = $this->database;
501
-            ++$i;
502
-        }
503
-        return $return;
504
-    }
220
+		if ($queryString == '') {
221
+			return 0;
222
+		}
223
+		if (!$this->connect()) {
224
+			return 0;
225
+			/* we already complained in connect() about that. */
226
+		}
227
+		$haltPrev = $this->haltOnError;
228
+		$this->haltOnError = 'no';
229
+		// New query, discard previous result.
230
+		if (is_resource($this->queryId)) {
231
+			$this->free();
232
+		}
233
+		if ($this->Debug) {
234
+			printf("Debug: query = %s<br>\n", $queryString);
235
+		}
236
+		if (isset($GLOBALS['log_queries']) && $GLOBALS['log_queries'] !== false) {
237
+			$this->log($queryString, $line, $file);
238
+		}
239
+		$tries = 3;
240
+		$try = 0;
241
+		$this->queryId = false;
242
+		while ((null === $this->queryId || $this->queryId === false) && $try <= $tries) {
243
+			$try++;
244
+			if ($try > 1) {
245
+				@mysqli_close($this->linkId);
246
+				$this->connect();
247
+			}
248
+			$start = microtime(true);
249
+			$onlyRollback = true;
250
+			$fails = -1;
251
+			while ($fails < 100 && (null === $this->queryId || $this->queryId === false)) {
252
+				$fails++;
253
+				try {
254
+					$this->queryId = @mysqli_query($this->linkId, $queryString, MYSQLI_STORE_RESULT);
255
+					if (in_array(@mysqli_errno($this->linkId), [2006, 3101, 1180])) {
256
+						//error_log("got ".@mysqli_errno($this->linkId)." sql error fails {$fails} on query {$queryString} from {$line}:{$file}");
257
+						usleep(500000); // 0.5 second
258
+					} else {
259
+						$onlyRollback = false;
260
+					}
261
+				} catch (\mysqli_sql_exception $e) {
262
+					if (in_array($e->getCode(), [2006, 3101, 1180])) {
263
+						//error_log("got ".$e->getCode()." sql error fails {$fails}");
264
+						usleep(500000); // 0.5 second
265
+					} else {
266
+						error_log('Got mysqli_sql_exception code '.$e->getCode().' error '.$e->getMessage().' on query '.$queryString.' from '.$line.':'.$file);
267
+						$onlyRollback = false;
268
+					}
269
+				}
270
+			}
271
+			if ($onlyRollback === true && false === $this->queryId) {
272
+				error_log('Got MySQLi 3101 Rollback Error '.$fails.' Times, Giving Up on '.$queryString.' from '.$line.':'.$file.' on '.__LINE__.':'.__FILE__);
273
+			}
274
+			$this->addLog($queryString, microtime(true) - $start, $line, $file);
275
+			$this->Row = 0;
276
+			$this->Errno = @mysqli_errno($this->linkId);
277
+			$this->Error = @mysqli_error($this->linkId);
278
+			if ($try == 1 && (null === $this->queryId || $this->queryId === false)) {
279
+				$this->emailError($queryString, 'Error #'.$this->Errno.': '.$this->Error, $line, $file);
280
+			}
281
+		}
282
+		$this->haltOnError = $haltPrev;
283
+		if (null === $this->queryId || $this->queryId === false) {
284
+			$this->halt('', $line, $file);
285
+		}
286
+
287
+		// Will return nada if it fails. That's fine.
288
+		return $this->queryId;
289
+	}
290
+
291
+	/**
292
+	 * @return array|null|object
293
+	 */
294
+	public function fetchObject()
295
+	{
296
+		$this->Record = @mysqli_fetch_object($this->queryId);
297
+		return $this->Record;
298
+	}
299
+
300
+	/* public: walk result set */
301
+
302
+	/**
303
+	 * Db::next_record()
304
+	 *
305
+	 * @param mixed $resultType
306
+	 * @return bool
307
+	 */
308
+	public function next_record($resultType = MYSQLI_BOTH)
309
+	{
310
+		if ($this->queryId === false) {
311
+			$this->haltmsg('next_record called with no query pending.');
312
+			return 0;
313
+		}
314
+
315
+		$this->Record = @mysqli_fetch_array($this->queryId, $resultType);
316
+		++$this->Row;
317
+		$this->Errno = mysqli_errno($this->linkId);
318
+		$this->Error = mysqli_error($this->linkId);
319
+
320
+		$stat = is_array($this->Record);
321
+		if (!$stat && $this->autoFree && is_resource($this->queryId)) {
322
+			$this->free();
323
+		}
324
+		return $stat;
325
+	}
326
+
327
+	/**
328
+	 * switch to position in result set
329
+	 *
330
+	 * @param integer $pos the row numbe starting at 0 to switch to
331
+	 * @return bool whetherit was successfu or not.
332
+	 */
333
+	public function seek($pos = 0)
334
+	{
335
+		$status = @mysqli_data_seek($this->queryId, $pos);
336
+		if ($status) {
337
+			$this->Row = $pos;
338
+		} else {
339
+			$this->haltmsg("seek({$pos}) failed: result has ".$this->num_rows().' rows', __LINE__, __FILE__);
340
+			/* half assed attempt to save the day, but do not consider this documented or even desirable behaviour. */
341
+			$rows = $this->num_rows();
342
+			@mysqli_data_seek($this->queryId, $rows);
343
+			$this->Row = $rows;
344
+			return false;
345
+		}
346
+		return true;
347
+	}
348
+
349
+	/**
350
+	 * Initiates a transaction
351
+	 *
352
+	 * @return bool
353
+	 */
354
+	public function transactionBegin()
355
+	{
356
+		if (version_compare(PHP_VERSION, '5.5.0') < 0) {
357
+			return true;
358
+		}
359
+		if (!$this->connect()) {
360
+			return 0;
361
+		}
362
+		return mysqli_begin_transaction($this->linkId);
363
+	}
364
+
365
+	/**
366
+	 * Commits a transaction
367
+	 *
368
+	 * @return bool
369
+	 */
370
+	public function transactionCommit()
371
+	{
372
+		if (version_compare(PHP_VERSION, '5.5.0') < 0 || $this->linkId === 0) {
373
+			return true;
374
+		}
375
+		return mysqli_commit($this->linkId);
376
+	}
377
+
378
+	/**
379
+	 * Rolls back a transaction
380
+	 *
381
+	 * @return bool
382
+	 */
383
+	public function transactionAbort()
384
+	{
385
+		if (version_compare(PHP_VERSION, '5.5.0') < 0 || $this->linkId === 0) {
386
+			return true;
387
+		}
388
+		return mysqli_rollback($this->linkId);
389
+	}
390
+
391
+	/**
392
+	 * This will get the last insert ID created on the current connection.  Should only be called after an insert query is
393
+	 * run on a table that has an auto incrementing field.  $table and $field are required, but unused here since it's
394
+	 * unnecessary for mysql.  For compatibility with pgsql, the params must be supplied.
395
+	 *
396
+	 * @param string $table
397
+	 * @param string $field
398
+	 * @return int|string
399
+	 */
400
+	public function getLastInsertId($table, $field)
401
+	{
402
+		if (!isset($table) || $table == '' || !isset($field) || $field == '') {
403
+			return -1;
404
+		}
405
+
406
+		return @mysqli_insert_id($this->linkId);
407
+	}
408
+
409
+	/* public: table locking */
410
+
411
+	/**
412
+	 * Db::lock()
413
+	 * @param mixed  $table
414
+	 * @param string $mode
415
+	 * @return bool|int|\mysqli_result
416
+	 */
417
+	public function lock($table, $mode = 'write')
418
+	{
419
+		$this->connect();
420
+		$query = 'lock tables ';
421
+		if (is_array($table)) {
422
+			foreach ($table as $key => $value) {
423
+				if ($key == 'read' && $key != 0) {
424
+					$query .= "$value read, ";
425
+				} else {
426
+					$query .= "$value $mode, ";
427
+				}
428
+			}
429
+			$query = mb_substr($query, 0, -2);
430
+		} else {
431
+			$query .= "$table $mode";
432
+		}
433
+		$res = @mysqli_query($this->linkId, $query);
434
+		if (!$res) {
435
+			$this->halt("lock($table, $mode) failed.");
436
+			return 0;
437
+		}
438
+		return $res;
439
+	}
440
+
441
+	/**
442
+	 * Db::unlock()
443
+	 * @param bool $haltOnError optional, defaults to TRUE, whether or not to halt on error
444
+	 * @return bool|int|\mysqli_result
445
+	 */
446
+	public function unlock($haltOnError = true)
447
+	{
448
+		$this->connect();
449
+
450
+		$res = @mysqli_query($this->linkId, 'unlock tables');
451
+		if ($haltOnError === true && !$res) {
452
+			$this->halt('unlock() failed.');
453
+			return 0;
454
+		}
455
+		return $res;
456
+	}
457
+
458
+	/* public: evaluate the result (size, width) */
459
+
460
+	/**
461
+	 * Db::affectedRows()
462
+	 * @return int
463
+	 */
464
+	public function affectedRows()
465
+	{
466
+		return @mysqli_affected_rows($this->linkId);
467
+	}
468
+
469
+	/**
470
+	 * Db::num_rows()
471
+	 * @return int
472
+	 */
473
+	public function num_rows()
474
+	{
475
+		return @mysqli_num_rows($this->queryId);
476
+	}
477
+
478
+	/**
479
+	 * Db::num_fields()
480
+	 * @return int
481
+	 */
482
+	public function num_fields()
483
+	{
484
+		return @mysqli_num_fields($this->queryId);
485
+	}
486
+
487
+	/**
488
+	 * gets an array of the table names in teh current datase
489
+	 *
490
+	 * @return array
491
+	 */
492
+	public function tableNames()
493
+	{
494
+		$return = [];
495
+		$this->query('SHOW TABLES');
496
+		$i = 0;
497
+		while ($info = $this->queryId->fetch_row()) {
498
+			$return[$i]['table_name'] = $info[0];
499
+			$return[$i]['tablespace_name'] = $this->database;
500
+			$return[$i]['database'] = $this->database;
501
+			++$i;
502
+		}
503
+		return $return;
504
+	}
505 505
 }
506 506
 
507 507
 /**
Please login to merge, or discard this patch.