Test Failed
Push — master ( 8f7507...698a1a )
by Joe
04:18
created
src/Mysqli/Db.php 1 patch
Indentation   +484 added lines, -484 removed lines patch added patch discarded remove patch
@@ -19,493 +19,493 @@
 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
-        if (!isset($GLOBALS['disable_db_queries'])) {
200
-            $this->addLog($query, microtime(true) - $start, $line, $file);
201
-        }
202
-        return $prepare;
203
-    }
204
-
205
-    /**
206
-     * Db::query()
207
-     *
208
-     *  Sends an SQL query to the database
209
-     *
210
-     * @param mixed $queryString
211
-     * @param string $line
212
-     * @param string $file
213
-     * @return mixed 0 if no query or query id handler, safe to ignore this return
214
-     */
215
-    public function query($queryString, $line = '', $file = '')
216
-    {
217
-        /* No empty queries, please, since PHP4 chokes on them. */
218
-        /* 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
+		if (!isset($GLOBALS['disable_db_queries'])) {
200
+			$this->addLog($query, microtime(true) - $start, $line, $file);
201
+		}
202
+		return $prepare;
203
+	}
204
+
205
+	/**
206
+	 * Db::query()
207
+	 *
208
+	 *  Sends an SQL query to the database
209
+	 *
210
+	 * @param mixed $queryString
211
+	 * @param string $line
212
+	 * @param string $file
213
+	 * @return mixed 0 if no query or query id handler, safe to ignore this return
214
+	 */
215
+	public function query($queryString, $line = '', $file = '')
216
+	{
217
+		/* No empty queries, please, since PHP4 chokes on them. */
218
+		/* The empty query string is passed on from the constructor,
219 219
         * when calling the class without a query, e.g. in situations
220 220
         * like these: '$db = new db_Subclass;'
221 221
         */
222
-        if ($queryString == '') {
223
-            return 0;
224
-        }
225
-        if (!$this->connect()) {
226
-            return 0;
227
-            /* we already complained in connect() about that. */
228
-        }
229
-        $haltPrev = $this->haltOnError;
230
-        $this->haltOnError = 'no';
231
-        // New query, discard previous result.
232
-        if (is_resource($this->queryId)) {
233
-            $this->free();
234
-        }
235
-        if ($this->Debug) {
236
-            printf("Debug: query = %s<br>\n", $queryString);
237
-        }
238
-        if (isset($GLOBALS['log_queries']) && $GLOBALS['log_queries'] !== false) {
239
-            $this->log($queryString, $line, $file);
240
-        }
241
-        $tries = 3;
242
-        $try = 0;
243
-        $this->queryId = false;
244
-        while ((null === $this->queryId || $this->queryId === false) && $try <= $tries) {
245
-            $try++;
246
-            if ($try > 1) {
247
-                @mysqli_close($this->linkId);
248
-                $this->connect();
249
-            }
250
-            $start = microtime(true);
251
-            $onlyRollback = true;
252
-            $fails = -1;
253
-            while ($fails < 100 && (null === $this->queryId || $this->queryId === false)) {
254
-                $fails++;
255
-                try {
256
-                    $this->queryId = @mysqli_query($this->linkId, $queryString, MYSQLI_STORE_RESULT);
257
-                    if (in_array(@mysqli_errno($this->linkId), [2006, 3101, 1180])) {
258
-                        //error_log("got ".@mysqli_errno($this->linkId)." sql error fails {$fails} on query {$queryString} from {$line}:{$file}");
259
-                        usleep(500000); // 0.5 second
260
-                    } else {
261
-                        $onlyRollback = false;
262
-                    }
263
-                } catch (\mysqli_sql_exception $e) {
264
-                    if (in_array($e->getCode(), [2006, 3101, 1180])) {
265
-                        //error_log("got ".$e->getCode()." sql error fails {$fails}");
266
-                        usleep(500000); // 0.5 second
267
-                    } else {
268
-                        error_log('Got mysqli_sql_exception code '.$e->getCode().' error '.$e->getMessage().' on query '.$queryString.' from '.$line.':'.$file);
269
-                        $onlyRollback = false;
270
-                    }
271
-                }
272
-            }
273
-            if ($onlyRollback === true && false === $this->queryId) {
274
-                error_log('Got MySQLi 3101 Rollback Error '.$fails.' Times, Giving Up on '.$queryString.' from '.$line.':'.$file.' on '.__LINE__.':'.__FILE__);
275
-            }
276
-            if (!isset($GLOBALS['disable_db_queries'])) {
277
-                $this->addLog($queryString, microtime(true) - $start, $line, $file);
278
-            }
279
-            $this->Row = 0;
280
-            $this->Errno = @mysqli_errno($this->linkId);
281
-            $this->Error = @mysqli_error($this->linkId);
282
-            if ($try == 1 && (null === $this->queryId || $this->queryId === false)) {
283
-                $this->emailError($queryString, 'Error #'.$this->Errno.': '.$this->Error, $line, $file);
284
-            }
285
-        }
286
-        $this->haltOnError = $haltPrev;
287
-        if (null === $this->queryId || $this->queryId === false) {
288
-            $this->halt('', $line, $file);
289
-        }
290
-
291
-        // Will return nada if it fails. That's fine.
292
-        return $this->queryId;
293
-    }
294
-
295
-    /**
296
-     * @return array|null|object
297
-     */
298
-    public function fetchObject()
299
-    {
300
-        $this->Record = @mysqli_fetch_object($this->queryId);
301
-        return $this->Record;
302
-    }
303
-
304
-    /* public: walk result set */
305
-
306
-    /**
307
-     * Db::next_record()
308
-     *
309
-     * @param mixed $resultType
310
-     * @return bool
311
-     */
312
-    public function next_record($resultType = MYSQLI_BOTH)
313
-    {
314
-        if ($this->queryId === false) {
315
-            $this->haltmsg('next_record called with no query pending.');
316
-            return 0;
317
-        }
318
-
319
-        $this->Record = @mysqli_fetch_array($this->queryId, $resultType);
320
-        ++$this->Row;
321
-        $this->Errno = mysqli_errno($this->linkId);
322
-        $this->Error = mysqli_error($this->linkId);
323
-
324
-        $stat = is_array($this->Record);
325
-        if (!$stat && $this->autoFree && is_resource($this->queryId)) {
326
-            $this->free();
327
-        }
328
-        return $stat;
329
-    }
330
-
331
-    /**
332
-     * switch to position in result set
333
-     *
334
-     * @param integer $pos the row numbe starting at 0 to switch to
335
-     * @return bool whetherit was successfu or not.
336
-     */
337
-    public function seek($pos = 0)
338
-    {
339
-        $status = @mysqli_data_seek($this->queryId, $pos);
340
-        if ($status) {
341
-            $this->Row = $pos;
342
-        } else {
343
-            $this->haltmsg("seek({$pos}) failed: result has ".$this->num_rows().' rows', __LINE__, __FILE__);
344
-            /* half assed attempt to save the day, but do not consider this documented or even desirable behaviour. */
345
-            $rows = $this->num_rows();
346
-            @mysqli_data_seek($this->queryId, $rows);
347
-            $this->Row = $rows;
348
-            return false;
349
-        }
350
-        return true;
351
-    }
352
-
353
-    /**
354
-     * Initiates a transaction
355
-     *
356
-     * @return bool
357
-     */
358
-    public function transactionBegin()
359
-    {
360
-        if (version_compare(PHP_VERSION, '5.5.0') < 0) {
361
-            return true;
362
-        }
363
-        if (!$this->connect()) {
364
-            return 0;
365
-        }
366
-        return mysqli_begin_transaction($this->linkId);
367
-    }
368
-
369
-    /**
370
-     * Commits a transaction
371
-     *
372
-     * @return bool
373
-     */
374
-    public function transactionCommit()
375
-    {
376
-        if (version_compare(PHP_VERSION, '5.5.0') < 0 || $this->linkId === 0) {
377
-            return true;
378
-        }
379
-        return mysqli_commit($this->linkId);
380
-    }
381
-
382
-    /**
383
-     * Rolls back a transaction
384
-     *
385
-     * @return bool
386
-     */
387
-    public function transactionAbort()
388
-    {
389
-        if (version_compare(PHP_VERSION, '5.5.0') < 0 || $this->linkId === 0) {
390
-            return true;
391
-        }
392
-        return mysqli_rollback($this->linkId);
393
-    }
394
-
395
-    /**
396
-     * This will get the last insert ID created on the current connection.  Should only be called after an insert query is
397
-     * run on a table that has an auto incrementing field.  $table and $field are required, but unused here since it's
398
-     * unnecessary for mysql.  For compatibility with pgsql, the params must be supplied.
399
-     *
400
-     * @param string $table
401
-     * @param string $field
402
-     * @return int|string
403
-     */
404
-    public function getLastInsertId($table, $field)
405
-    {
406
-        if (!isset($table) || $table == '' || !isset($field) || $field == '') {
407
-            return -1;
408
-        }
409
-
410
-        return @mysqli_insert_id($this->linkId);
411
-    }
412
-
413
-    /* public: table locking */
414
-
415
-    /**
416
-     * Db::lock()
417
-     * @param mixed  $table
418
-     * @param string $mode
419
-     * @return bool|int|\mysqli_result
420
-     */
421
-    public function lock($table, $mode = 'write')
422
-    {
423
-        $this->connect();
424
-        $query = 'lock tables ';
425
-        if (is_array($table)) {
426
-            foreach ($table as $key => $value) {
427
-                if ($key == 'read' && $key != 0) {
428
-                    $query .= "$value read, ";
429
-                } else {
430
-                    $query .= "$value $mode, ";
431
-                }
432
-            }
433
-            $query = mb_substr($query, 0, -2);
434
-        } else {
435
-            $query .= "$table $mode";
436
-        }
437
-        $res = @mysqli_query($this->linkId, $query);
438
-        if (!$res) {
439
-            $this->halt("lock($table, $mode) failed.");
440
-            return 0;
441
-        }
442
-        return $res;
443
-    }
444
-
445
-    /**
446
-     * Db::unlock()
447
-     * @param bool $haltOnError optional, defaults to TRUE, whether or not to halt on error
448
-     * @return bool|int|\mysqli_result
449
-     */
450
-    public function unlock($haltOnError = true)
451
-    {
452
-        $this->connect();
453
-
454
-        $res = @mysqli_query($this->linkId, 'unlock tables');
455
-        if ($haltOnError === true && !$res) {
456
-            $this->halt('unlock() failed.');
457
-            return 0;
458
-        }
459
-        return $res;
460
-    }
461
-
462
-    /* public: evaluate the result (size, width) */
463
-
464
-    /**
465
-     * Db::affectedRows()
466
-     * @return int
467
-     */
468
-    public function affectedRows()
469
-    {
470
-        return @mysqli_affected_rows($this->linkId);
471
-    }
472
-
473
-    /**
474
-     * Db::num_rows()
475
-     * @return int
476
-     */
477
-    public function num_rows()
478
-    {
479
-        return @mysqli_num_rows($this->queryId);
480
-    }
481
-
482
-    /**
483
-     * Db::num_fields()
484
-     * @return int
485
-     */
486
-    public function num_fields()
487
-    {
488
-        return @mysqli_num_fields($this->queryId);
489
-    }
490
-
491
-    /**
492
-     * gets an array of the table names in teh current datase
493
-     *
494
-     * @return array
495
-     */
496
-    public function tableNames()
497
-    {
498
-        $return = [];
499
-        $this->query('SHOW TABLES');
500
-        $i = 0;
501
-        while ($info = $this->queryId->fetch_row()) {
502
-            $return[$i]['table_name'] = $info[0];
503
-            $return[$i]['tablespace_name'] = $this->database;
504
-            $return[$i]['database'] = $this->database;
505
-            ++$i;
506
-        }
507
-        return $return;
508
-    }
222
+		if ($queryString == '') {
223
+			return 0;
224
+		}
225
+		if (!$this->connect()) {
226
+			return 0;
227
+			/* we already complained in connect() about that. */
228
+		}
229
+		$haltPrev = $this->haltOnError;
230
+		$this->haltOnError = 'no';
231
+		// New query, discard previous result.
232
+		if (is_resource($this->queryId)) {
233
+			$this->free();
234
+		}
235
+		if ($this->Debug) {
236
+			printf("Debug: query = %s<br>\n", $queryString);
237
+		}
238
+		if (isset($GLOBALS['log_queries']) && $GLOBALS['log_queries'] !== false) {
239
+			$this->log($queryString, $line, $file);
240
+		}
241
+		$tries = 3;
242
+		$try = 0;
243
+		$this->queryId = false;
244
+		while ((null === $this->queryId || $this->queryId === false) && $try <= $tries) {
245
+			$try++;
246
+			if ($try > 1) {
247
+				@mysqli_close($this->linkId);
248
+				$this->connect();
249
+			}
250
+			$start = microtime(true);
251
+			$onlyRollback = true;
252
+			$fails = -1;
253
+			while ($fails < 100 && (null === $this->queryId || $this->queryId === false)) {
254
+				$fails++;
255
+				try {
256
+					$this->queryId = @mysqli_query($this->linkId, $queryString, MYSQLI_STORE_RESULT);
257
+					if (in_array(@mysqli_errno($this->linkId), [2006, 3101, 1180])) {
258
+						//error_log("got ".@mysqli_errno($this->linkId)." sql error fails {$fails} on query {$queryString} from {$line}:{$file}");
259
+						usleep(500000); // 0.5 second
260
+					} else {
261
+						$onlyRollback = false;
262
+					}
263
+				} catch (\mysqli_sql_exception $e) {
264
+					if (in_array($e->getCode(), [2006, 3101, 1180])) {
265
+						//error_log("got ".$e->getCode()." sql error fails {$fails}");
266
+						usleep(500000); // 0.5 second
267
+					} else {
268
+						error_log('Got mysqli_sql_exception code '.$e->getCode().' error '.$e->getMessage().' on query '.$queryString.' from '.$line.':'.$file);
269
+						$onlyRollback = false;
270
+					}
271
+				}
272
+			}
273
+			if ($onlyRollback === true && false === $this->queryId) {
274
+				error_log('Got MySQLi 3101 Rollback Error '.$fails.' Times, Giving Up on '.$queryString.' from '.$line.':'.$file.' on '.__LINE__.':'.__FILE__);
275
+			}
276
+			if (!isset($GLOBALS['disable_db_queries'])) {
277
+				$this->addLog($queryString, microtime(true) - $start, $line, $file);
278
+			}
279
+			$this->Row = 0;
280
+			$this->Errno = @mysqli_errno($this->linkId);
281
+			$this->Error = @mysqli_error($this->linkId);
282
+			if ($try == 1 && (null === $this->queryId || $this->queryId === false)) {
283
+				$this->emailError($queryString, 'Error #'.$this->Errno.': '.$this->Error, $line, $file);
284
+			}
285
+		}
286
+		$this->haltOnError = $haltPrev;
287
+		if (null === $this->queryId || $this->queryId === false) {
288
+			$this->halt('', $line, $file);
289
+		}
290
+
291
+		// Will return nada if it fails. That's fine.
292
+		return $this->queryId;
293
+	}
294
+
295
+	/**
296
+	 * @return array|null|object
297
+	 */
298
+	public function fetchObject()
299
+	{
300
+		$this->Record = @mysqli_fetch_object($this->queryId);
301
+		return $this->Record;
302
+	}
303
+
304
+	/* public: walk result set */
305
+
306
+	/**
307
+	 * Db::next_record()
308
+	 *
309
+	 * @param mixed $resultType
310
+	 * @return bool
311
+	 */
312
+	public function next_record($resultType = MYSQLI_BOTH)
313
+	{
314
+		if ($this->queryId === false) {
315
+			$this->haltmsg('next_record called with no query pending.');
316
+			return 0;
317
+		}
318
+
319
+		$this->Record = @mysqli_fetch_array($this->queryId, $resultType);
320
+		++$this->Row;
321
+		$this->Errno = mysqli_errno($this->linkId);
322
+		$this->Error = mysqli_error($this->linkId);
323
+
324
+		$stat = is_array($this->Record);
325
+		if (!$stat && $this->autoFree && is_resource($this->queryId)) {
326
+			$this->free();
327
+		}
328
+		return $stat;
329
+	}
330
+
331
+	/**
332
+	 * switch to position in result set
333
+	 *
334
+	 * @param integer $pos the row numbe starting at 0 to switch to
335
+	 * @return bool whetherit was successfu or not.
336
+	 */
337
+	public function seek($pos = 0)
338
+	{
339
+		$status = @mysqli_data_seek($this->queryId, $pos);
340
+		if ($status) {
341
+			$this->Row = $pos;
342
+		} else {
343
+			$this->haltmsg("seek({$pos}) failed: result has ".$this->num_rows().' rows', __LINE__, __FILE__);
344
+			/* half assed attempt to save the day, but do not consider this documented or even desirable behaviour. */
345
+			$rows = $this->num_rows();
346
+			@mysqli_data_seek($this->queryId, $rows);
347
+			$this->Row = $rows;
348
+			return false;
349
+		}
350
+		return true;
351
+	}
352
+
353
+	/**
354
+	 * Initiates a transaction
355
+	 *
356
+	 * @return bool
357
+	 */
358
+	public function transactionBegin()
359
+	{
360
+		if (version_compare(PHP_VERSION, '5.5.0') < 0) {
361
+			return true;
362
+		}
363
+		if (!$this->connect()) {
364
+			return 0;
365
+		}
366
+		return mysqli_begin_transaction($this->linkId);
367
+	}
368
+
369
+	/**
370
+	 * Commits a transaction
371
+	 *
372
+	 * @return bool
373
+	 */
374
+	public function transactionCommit()
375
+	{
376
+		if (version_compare(PHP_VERSION, '5.5.0') < 0 || $this->linkId === 0) {
377
+			return true;
378
+		}
379
+		return mysqli_commit($this->linkId);
380
+	}
381
+
382
+	/**
383
+	 * Rolls back a transaction
384
+	 *
385
+	 * @return bool
386
+	 */
387
+	public function transactionAbort()
388
+	{
389
+		if (version_compare(PHP_VERSION, '5.5.0') < 0 || $this->linkId === 0) {
390
+			return true;
391
+		}
392
+		return mysqli_rollback($this->linkId);
393
+	}
394
+
395
+	/**
396
+	 * This will get the last insert ID created on the current connection.  Should only be called after an insert query is
397
+	 * run on a table that has an auto incrementing field.  $table and $field are required, but unused here since it's
398
+	 * unnecessary for mysql.  For compatibility with pgsql, the params must be supplied.
399
+	 *
400
+	 * @param string $table
401
+	 * @param string $field
402
+	 * @return int|string
403
+	 */
404
+	public function getLastInsertId($table, $field)
405
+	{
406
+		if (!isset($table) || $table == '' || !isset($field) || $field == '') {
407
+			return -1;
408
+		}
409
+
410
+		return @mysqli_insert_id($this->linkId);
411
+	}
412
+
413
+	/* public: table locking */
414
+
415
+	/**
416
+	 * Db::lock()
417
+	 * @param mixed  $table
418
+	 * @param string $mode
419
+	 * @return bool|int|\mysqli_result
420
+	 */
421
+	public function lock($table, $mode = 'write')
422
+	{
423
+		$this->connect();
424
+		$query = 'lock tables ';
425
+		if (is_array($table)) {
426
+			foreach ($table as $key => $value) {
427
+				if ($key == 'read' && $key != 0) {
428
+					$query .= "$value read, ";
429
+				} else {
430
+					$query .= "$value $mode, ";
431
+				}
432
+			}
433
+			$query = mb_substr($query, 0, -2);
434
+		} else {
435
+			$query .= "$table $mode";
436
+		}
437
+		$res = @mysqli_query($this->linkId, $query);
438
+		if (!$res) {
439
+			$this->halt("lock($table, $mode) failed.");
440
+			return 0;
441
+		}
442
+		return $res;
443
+	}
444
+
445
+	/**
446
+	 * Db::unlock()
447
+	 * @param bool $haltOnError optional, defaults to TRUE, whether or not to halt on error
448
+	 * @return bool|int|\mysqli_result
449
+	 */
450
+	public function unlock($haltOnError = true)
451
+	{
452
+		$this->connect();
453
+
454
+		$res = @mysqli_query($this->linkId, 'unlock tables');
455
+		if ($haltOnError === true && !$res) {
456
+			$this->halt('unlock() failed.');
457
+			return 0;
458
+		}
459
+		return $res;
460
+	}
461
+
462
+	/* public: evaluate the result (size, width) */
463
+
464
+	/**
465
+	 * Db::affectedRows()
466
+	 * @return int
467
+	 */
468
+	public function affectedRows()
469
+	{
470
+		return @mysqli_affected_rows($this->linkId);
471
+	}
472
+
473
+	/**
474
+	 * Db::num_rows()
475
+	 * @return int
476
+	 */
477
+	public function num_rows()
478
+	{
479
+		return @mysqli_num_rows($this->queryId);
480
+	}
481
+
482
+	/**
483
+	 * Db::num_fields()
484
+	 * @return int
485
+	 */
486
+	public function num_fields()
487
+	{
488
+		return @mysqli_num_fields($this->queryId);
489
+	}
490
+
491
+	/**
492
+	 * gets an array of the table names in teh current datase
493
+	 *
494
+	 * @return array
495
+	 */
496
+	public function tableNames()
497
+	{
498
+		$return = [];
499
+		$this->query('SHOW TABLES');
500
+		$i = 0;
501
+		while ($info = $this->queryId->fetch_row()) {
502
+			$return[$i]['table_name'] = $info[0];
503
+			$return[$i]['tablespace_name'] = $this->database;
504
+			$return[$i]['database'] = $this->database;
505
+			++$i;
506
+		}
507
+		return $return;
508
+	}
509 509
 }
510 510
 
511 511
 /**
Please login to merge, or discard this patch.