Test Failed
Push — master ( 92cb25...8382ce )
by Joe
13:46
created
src/Mysqli/Db.php 2 patches
Indentation   +494 added lines, -494 removed lines patch added patch discarded remove patch
@@ -19,503 +19,503 @@
 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 >= $this->maxConnectErrors - 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. ".$this->linkId->connect_error);
86
-                return 0;
87
-            }
88
-            //error_log("real_connect($host, $user, $password, $database, $port)");
89
-            $this->linkId = mysqli_init();
90
-            $this->linkId->options(MYSQLI_INIT_COMMAND, "SET NAMES {$this->characterSet} COLLATE {$this->collation}, COLLATION_CONNECTION = {$this->collation}, COLLATION_DATABASE = {$this->collation}");
91
-            if (!$this->linkId->real_connect($host, $user, $password, $database, $port != '' ? $port : NULL)) {
92
-                $this->halt("connect($host, $user, \$password) failed. ".$this->linkId->connect_error);
93
-                return 0;
94
-            }
95
-            $this->linkId->set_charset($this->characterSet);
96
-            if ($this->linkId->connect_errno) {
97
-                $this->halt("connect($host, $user, \$password) failed. ".$this->linkId->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 >= $this->maxConnectErrors - 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. ".$this->linkId->connect_error);
86
+				return 0;
87
+			}
88
+			//error_log("real_connect($host, $user, $password, $database, $port)");
89
+			$this->linkId = mysqli_init();
90
+			$this->linkId->options(MYSQLI_INIT_COMMAND, "SET NAMES {$this->characterSet} COLLATE {$this->collation}, COLLATION_CONNECTION = {$this->collation}, COLLATION_DATABASE = {$this->collation}");
91
+			if (!$this->linkId->real_connect($host, $user, $password, $database, $port != '' ? $port : NULL)) {
92
+				$this->halt("connect($host, $user, \$password) failed. ".$this->linkId->connect_error);
93
+				return 0;
94
+			}
95
+			$this->linkId->set_charset($this->characterSet);
96
+			if ($this->linkId->connect_errno) {
97
+				$this->halt("connect($host, $user, \$password) failed. ".$this->linkId->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 = 2;
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->linkId = 0;
249
-            }
250
-            $start = microtime(true);
251
-            $onlyRollback = true;
252
-            $fails = -1;
253
-            while ($fails < 30 && (null === $this->queryId || $this->queryId === false)) {
254
-                $this->connect();
255
-                $fails++;
256
-                try {
257
-                    $this->queryId = @mysqli_query($this->linkId, $queryString, MYSQLI_STORE_RESULT);
258
-                    if (in_array((int)@mysqli_errno($this->linkId), [1213, 2006, 3101, 1180])) {
259
-                        //error_log("got ".@mysqli_errno($this->linkId)." sql error fails {$fails} on query {$queryString} from {$line}:{$file}");
260
-                        usleep(250000); // 0.25 second
261
-                    } else {
262
-                        $onlyRollback = false;
263
-                        if (in_array((int)@mysqli_errno($this->linkId), [1064])) {
264
-                            $tries = 0;
265
-                        }
266
-                        break;
267
-                    }
268
-                } catch (\mysqli_sql_exception $e) {
269
-                    if (in_array((int)$e->getCode(), [1213, 2006, 3101, 1180])) {
270
-                        //error_log("got ".$e->getCode()." sql error fails {$fails}");
271
-                        usleep(250000); // 0.25 second
272
-                    } else {
273
-                        error_log('Got mysqli_sql_exception code '.$e->getCode().' error '.$e->getMessage().' on query '.$queryString.' from '.$line.':'.$file);
274
-                        $onlyRollback = false;
275
-                        if (in_array((int)@mysqli_errno($this->linkId), [1064])) {
276
-                            $tries = 0;
277
-                        }
278
-                        break;
279
-                    }
280
-                }
281
-            }
282
-            if (!isset($GLOBALS['disable_db_queries'])) {
283
-                $this->addLog($queryString, microtime(true) - $start, $line, $file);
284
-            }
285
-            $this->Row = 0;
286
-            $this->Errno = @mysqli_errno($this->linkId);
287
-            $this->Error = @mysqli_error($this->linkId);
288
-            if ($try == 1 && (null === $this->queryId || $this->queryId === false)) {
289
-                //$this->emailError($queryString, 'Error #'.$this->Errno.': '.$this->Error, $line, $file);
290
-            }
291
-        }
292
-        $this->haltOnError = $haltPrev;
293
-        if ($onlyRollback === true && false === $this->queryId) {
294
-            error_log('Got MySQLi 3101 Rollback Error '.$fails.' Times, Giving Up on '.$queryString.' from '.$line.':'.$file.' on '.__LINE__.':'.__FILE__);
295
-        }
296
-        if (null === $this->queryId || $this->queryId === false) {
297
-            $this->emailError($queryString, 'Error #'.$this->Errno.': '.$this->Error, $line, $file);
298
-            $this->halt('', $line, $file);
299
-        }
300
-
301
-        // Will return nada if it fails. That's fine.
302
-        return $this->queryId;
303
-    }
304
-
305
-    /**
306
-     * @return array|null|object
307
-     */
308
-    public function fetchObject()
309
-    {
310
-        $this->Record = @mysqli_fetch_object($this->queryId);
311
-        return $this->Record;
312
-    }
313
-
314
-    /* public: walk result set */
315
-
316
-    /**
317
-     * Db::next_record()
318
-     *
319
-     * @param mixed $resultType
320
-     * @return bool
321
-     */
322
-    public function next_record($resultType = MYSQLI_BOTH)
323
-    {
324
-        if ($this->queryId === false) {
325
-            $this->haltmsg('next_record called with no query pending.');
326
-            return 0;
327
-        }
328
-
329
-        $this->Record = @mysqli_fetch_array($this->queryId, $resultType);
330
-        ++$this->Row;
331
-        $this->Errno = mysqli_errno($this->linkId);
332
-        $this->Error = mysqli_error($this->linkId);
333
-
334
-        $stat = is_array($this->Record);
335
-        if (!$stat && $this->autoFree && is_resource($this->queryId)) {
336
-            $this->free();
337
-        }
338
-        return $stat;
339
-    }
340
-
341
-    /**
342
-     * switch to position in result set
343
-     *
344
-     * @param integer $pos the row numbe starting at 0 to switch to
345
-     * @return bool whetherit was successfu or not.
346
-     */
347
-    public function seek($pos = 0)
348
-    {
349
-        $status = @mysqli_data_seek($this->queryId, $pos);
350
-        if ($status) {
351
-            $this->Row = $pos;
352
-        } else {
353
-            $this->haltmsg("seek({$pos}) failed: result has ".$this->num_rows().' rows', __LINE__, __FILE__);
354
-            /* half assed attempt to save the day, but do not consider this documented or even desirable behaviour. */
355
-            $rows = $this->num_rows();
356
-            @mysqli_data_seek($this->queryId, $rows);
357
-            $this->Row = $rows;
358
-            return false;
359
-        }
360
-        return true;
361
-    }
362
-
363
-    /**
364
-     * Initiates a transaction
365
-     *
366
-     * @return bool
367
-     */
368
-    public function transactionBegin()
369
-    {
370
-        if (version_compare(PHP_VERSION, '5.5.0') < 0) {
371
-            return true;
372
-        }
373
-        if (!$this->connect()) {
374
-            return 0;
375
-        }
376
-        return mysqli_begin_transaction($this->linkId);
377
-    }
378
-
379
-    /**
380
-     * Commits a transaction
381
-     *
382
-     * @return bool
383
-     */
384
-    public function transactionCommit()
385
-    {
386
-        if (version_compare(PHP_VERSION, '5.5.0') < 0 || $this->linkId === 0) {
387
-            return true;
388
-        }
389
-        return mysqli_commit($this->linkId);
390
-    }
391
-
392
-    /**
393
-     * Rolls back a transaction
394
-     *
395
-     * @return bool
396
-     */
397
-    public function transactionAbort()
398
-    {
399
-        if (version_compare(PHP_VERSION, '5.5.0') < 0 || $this->linkId === 0) {
400
-            return true;
401
-        }
402
-        return mysqli_rollback($this->linkId);
403
-    }
404
-
405
-    /**
406
-     * This will get the last insert ID created on the current connection.  Should only be called after an insert query is
407
-     * run on a table that has an auto incrementing field.  $table and $field are required, but unused here since it's
408
-     * unnecessary for mysql.  For compatibility with pgsql, the params must be supplied.
409
-     *
410
-     * @param string $table
411
-     * @param string $field
412
-     * @return int|string
413
-     */
414
-    public function getLastInsertId($table, $field)
415
-    {
416
-        if (!isset($table) || $table == '' || !isset($field) || $field == '') {
417
-            return -1;
418
-        }
419
-
420
-        return @mysqli_insert_id($this->linkId);
421
-    }
422
-
423
-    /* public: table locking */
424
-
425
-    /**
426
-     * Db::lock()
427
-     * @param mixed  $table
428
-     * @param string $mode
429
-     * @return bool|int|\mysqli_result
430
-     */
431
-    public function lock($table, $mode = 'write')
432
-    {
433
-        $this->connect();
434
-        $query = 'lock tables ';
435
-        if (is_array($table)) {
436
-            foreach ($table as $key => $value) {
437
-                if ($key == 'read' && $key != 0) {
438
-                    $query .= "$value read, ";
439
-                } else {
440
-                    $query .= "$value $mode, ";
441
-                }
442
-            }
443
-            $query = mb_substr($query, 0, -2);
444
-        } else {
445
-            $query .= "$table $mode";
446
-        }
447
-        $res = @mysqli_query($this->linkId, $query);
448
-        if (!$res) {
449
-            $this->halt("lock($table, $mode) failed.");
450
-            return 0;
451
-        }
452
-        return $res;
453
-    }
454
-
455
-    /**
456
-     * Db::unlock()
457
-     * @param bool $haltOnError optional, defaults to TRUE, whether or not to halt on error
458
-     * @return bool|int|\mysqli_result
459
-     */
460
-    public function unlock($haltOnError = true)
461
-    {
462
-        $this->connect();
463
-
464
-        $res = @mysqli_query($this->linkId, 'unlock tables');
465
-        if ($haltOnError === true && !$res) {
466
-            $this->halt('unlock() failed.');
467
-            return 0;
468
-        }
469
-        return $res;
470
-    }
471
-
472
-    /* public: evaluate the result (size, width) */
473
-
474
-    /**
475
-     * Db::affectedRows()
476
-     * @return int
477
-     */
478
-    public function affectedRows()
479
-    {
480
-        return @mysqli_affected_rows($this->linkId);
481
-    }
482
-
483
-    /**
484
-     * Db::num_rows()
485
-     * @return int
486
-     */
487
-    public function num_rows()
488
-    {
489
-        return @mysqli_num_rows($this->queryId);
490
-    }
491
-
492
-    /**
493
-     * Db::num_fields()
494
-     * @return int
495
-     */
496
-    public function num_fields()
497
-    {
498
-        return @mysqli_num_fields($this->queryId);
499
-    }
500
-
501
-    /**
502
-     * gets an array of the table names in teh current datase
503
-     *
504
-     * @return array
505
-     */
506
-    public function tableNames()
507
-    {
508
-        $return = [];
509
-        $this->query('SHOW TABLES');
510
-        $i = 0;
511
-        while ($info = $this->queryId->fetch_row()) {
512
-            $return[$i]['table_name'] = $info[0];
513
-            $return[$i]['tablespace_name'] = $this->database;
514
-            $return[$i]['database'] = $this->database;
515
-            ++$i;
516
-        }
517
-        return $return;
518
-    }
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 = 2;
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->linkId = 0;
249
+			}
250
+			$start = microtime(true);
251
+			$onlyRollback = true;
252
+			$fails = -1;
253
+			while ($fails < 30 && (null === $this->queryId || $this->queryId === false)) {
254
+				$this->connect();
255
+				$fails++;
256
+				try {
257
+					$this->queryId = @mysqli_query($this->linkId, $queryString, MYSQLI_STORE_RESULT);
258
+					if (in_array((int)@mysqli_errno($this->linkId), [1213, 2006, 3101, 1180])) {
259
+						//error_log("got ".@mysqli_errno($this->linkId)." sql error fails {$fails} on query {$queryString} from {$line}:{$file}");
260
+						usleep(250000); // 0.25 second
261
+					} else {
262
+						$onlyRollback = false;
263
+						if (in_array((int)@mysqli_errno($this->linkId), [1064])) {
264
+							$tries = 0;
265
+						}
266
+						break;
267
+					}
268
+				} catch (\mysqli_sql_exception $e) {
269
+					if (in_array((int)$e->getCode(), [1213, 2006, 3101, 1180])) {
270
+						//error_log("got ".$e->getCode()." sql error fails {$fails}");
271
+						usleep(250000); // 0.25 second
272
+					} else {
273
+						error_log('Got mysqli_sql_exception code '.$e->getCode().' error '.$e->getMessage().' on query '.$queryString.' from '.$line.':'.$file);
274
+						$onlyRollback = false;
275
+						if (in_array((int)@mysqli_errno($this->linkId), [1064])) {
276
+							$tries = 0;
277
+						}
278
+						break;
279
+					}
280
+				}
281
+			}
282
+			if (!isset($GLOBALS['disable_db_queries'])) {
283
+				$this->addLog($queryString, microtime(true) - $start, $line, $file);
284
+			}
285
+			$this->Row = 0;
286
+			$this->Errno = @mysqli_errno($this->linkId);
287
+			$this->Error = @mysqli_error($this->linkId);
288
+			if ($try == 1 && (null === $this->queryId || $this->queryId === false)) {
289
+				//$this->emailError($queryString, 'Error #'.$this->Errno.': '.$this->Error, $line, $file);
290
+			}
291
+		}
292
+		$this->haltOnError = $haltPrev;
293
+		if ($onlyRollback === true && false === $this->queryId) {
294
+			error_log('Got MySQLi 3101 Rollback Error '.$fails.' Times, Giving Up on '.$queryString.' from '.$line.':'.$file.' on '.__LINE__.':'.__FILE__);
295
+		}
296
+		if (null === $this->queryId || $this->queryId === false) {
297
+			$this->emailError($queryString, 'Error #'.$this->Errno.': '.$this->Error, $line, $file);
298
+			$this->halt('', $line, $file);
299
+		}
300
+
301
+		// Will return nada if it fails. That's fine.
302
+		return $this->queryId;
303
+	}
304
+
305
+	/**
306
+	 * @return array|null|object
307
+	 */
308
+	public function fetchObject()
309
+	{
310
+		$this->Record = @mysqli_fetch_object($this->queryId);
311
+		return $this->Record;
312
+	}
313
+
314
+	/* public: walk result set */
315
+
316
+	/**
317
+	 * Db::next_record()
318
+	 *
319
+	 * @param mixed $resultType
320
+	 * @return bool
321
+	 */
322
+	public function next_record($resultType = MYSQLI_BOTH)
323
+	{
324
+		if ($this->queryId === false) {
325
+			$this->haltmsg('next_record called with no query pending.');
326
+			return 0;
327
+		}
328
+
329
+		$this->Record = @mysqli_fetch_array($this->queryId, $resultType);
330
+		++$this->Row;
331
+		$this->Errno = mysqli_errno($this->linkId);
332
+		$this->Error = mysqli_error($this->linkId);
333
+
334
+		$stat = is_array($this->Record);
335
+		if (!$stat && $this->autoFree && is_resource($this->queryId)) {
336
+			$this->free();
337
+		}
338
+		return $stat;
339
+	}
340
+
341
+	/**
342
+	 * switch to position in result set
343
+	 *
344
+	 * @param integer $pos the row numbe starting at 0 to switch to
345
+	 * @return bool whetherit was successfu or not.
346
+	 */
347
+	public function seek($pos = 0)
348
+	{
349
+		$status = @mysqli_data_seek($this->queryId, $pos);
350
+		if ($status) {
351
+			$this->Row = $pos;
352
+		} else {
353
+			$this->haltmsg("seek({$pos}) failed: result has ".$this->num_rows().' rows', __LINE__, __FILE__);
354
+			/* half assed attempt to save the day, but do not consider this documented or even desirable behaviour. */
355
+			$rows = $this->num_rows();
356
+			@mysqli_data_seek($this->queryId, $rows);
357
+			$this->Row = $rows;
358
+			return false;
359
+		}
360
+		return true;
361
+	}
362
+
363
+	/**
364
+	 * Initiates a transaction
365
+	 *
366
+	 * @return bool
367
+	 */
368
+	public function transactionBegin()
369
+	{
370
+		if (version_compare(PHP_VERSION, '5.5.0') < 0) {
371
+			return true;
372
+		}
373
+		if (!$this->connect()) {
374
+			return 0;
375
+		}
376
+		return mysqli_begin_transaction($this->linkId);
377
+	}
378
+
379
+	/**
380
+	 * Commits a transaction
381
+	 *
382
+	 * @return bool
383
+	 */
384
+	public function transactionCommit()
385
+	{
386
+		if (version_compare(PHP_VERSION, '5.5.0') < 0 || $this->linkId === 0) {
387
+			return true;
388
+		}
389
+		return mysqli_commit($this->linkId);
390
+	}
391
+
392
+	/**
393
+	 * Rolls back a transaction
394
+	 *
395
+	 * @return bool
396
+	 */
397
+	public function transactionAbort()
398
+	{
399
+		if (version_compare(PHP_VERSION, '5.5.0') < 0 || $this->linkId === 0) {
400
+			return true;
401
+		}
402
+		return mysqli_rollback($this->linkId);
403
+	}
404
+
405
+	/**
406
+	 * This will get the last insert ID created on the current connection.  Should only be called after an insert query is
407
+	 * run on a table that has an auto incrementing field.  $table and $field are required, but unused here since it's
408
+	 * unnecessary for mysql.  For compatibility with pgsql, the params must be supplied.
409
+	 *
410
+	 * @param string $table
411
+	 * @param string $field
412
+	 * @return int|string
413
+	 */
414
+	public function getLastInsertId($table, $field)
415
+	{
416
+		if (!isset($table) || $table == '' || !isset($field) || $field == '') {
417
+			return -1;
418
+		}
419
+
420
+		return @mysqli_insert_id($this->linkId);
421
+	}
422
+
423
+	/* public: table locking */
424
+
425
+	/**
426
+	 * Db::lock()
427
+	 * @param mixed  $table
428
+	 * @param string $mode
429
+	 * @return bool|int|\mysqli_result
430
+	 */
431
+	public function lock($table, $mode = 'write')
432
+	{
433
+		$this->connect();
434
+		$query = 'lock tables ';
435
+		if (is_array($table)) {
436
+			foreach ($table as $key => $value) {
437
+				if ($key == 'read' && $key != 0) {
438
+					$query .= "$value read, ";
439
+				} else {
440
+					$query .= "$value $mode, ";
441
+				}
442
+			}
443
+			$query = mb_substr($query, 0, -2);
444
+		} else {
445
+			$query .= "$table $mode";
446
+		}
447
+		$res = @mysqli_query($this->linkId, $query);
448
+		if (!$res) {
449
+			$this->halt("lock($table, $mode) failed.");
450
+			return 0;
451
+		}
452
+		return $res;
453
+	}
454
+
455
+	/**
456
+	 * Db::unlock()
457
+	 * @param bool $haltOnError optional, defaults to TRUE, whether or not to halt on error
458
+	 * @return bool|int|\mysqli_result
459
+	 */
460
+	public function unlock($haltOnError = true)
461
+	{
462
+		$this->connect();
463
+
464
+		$res = @mysqli_query($this->linkId, 'unlock tables');
465
+		if ($haltOnError === true && !$res) {
466
+			$this->halt('unlock() failed.');
467
+			return 0;
468
+		}
469
+		return $res;
470
+	}
471
+
472
+	/* public: evaluate the result (size, width) */
473
+
474
+	/**
475
+	 * Db::affectedRows()
476
+	 * @return int
477
+	 */
478
+	public function affectedRows()
479
+	{
480
+		return @mysqli_affected_rows($this->linkId);
481
+	}
482
+
483
+	/**
484
+	 * Db::num_rows()
485
+	 * @return int
486
+	 */
487
+	public function num_rows()
488
+	{
489
+		return @mysqli_num_rows($this->queryId);
490
+	}
491
+
492
+	/**
493
+	 * Db::num_fields()
494
+	 * @return int
495
+	 */
496
+	public function num_fields()
497
+	{
498
+		return @mysqli_num_fields($this->queryId);
499
+	}
500
+
501
+	/**
502
+	 * gets an array of the table names in teh current datase
503
+	 *
504
+	 * @return array
505
+	 */
506
+	public function tableNames()
507
+	{
508
+		$return = [];
509
+		$this->query('SHOW TABLES');
510
+		$i = 0;
511
+		while ($info = $this->queryId->fetch_row()) {
512
+			$return[$i]['table_name'] = $info[0];
513
+			$return[$i]['tablespace_name'] = $this->database;
514
+			$return[$i]['database'] = $this->database;
515
+			++$i;
516
+		}
517
+		return $return;
518
+	}
519 519
 }
520 520
 
521 521
 /**
Please login to merge, or discard this patch.
Spacing   +4 added lines, -4 removed lines patch added patch discarded remove patch
@@ -255,24 +255,24 @@
 block discarded – undo
255 255
                 $fails++;
256 256
                 try {
257 257
                     $this->queryId = @mysqli_query($this->linkId, $queryString, MYSQLI_STORE_RESULT);
258
-                    if (in_array((int)@mysqli_errno($this->linkId), [1213, 2006, 3101, 1180])) {
258
+                    if (in_array((int) @mysqli_errno($this->linkId), [1213, 2006, 3101, 1180])) {
259 259
                         //error_log("got ".@mysqli_errno($this->linkId)." sql error fails {$fails} on query {$queryString} from {$line}:{$file}");
260 260
                         usleep(250000); // 0.25 second
261 261
                     } else {
262 262
                         $onlyRollback = false;
263
-                        if (in_array((int)@mysqli_errno($this->linkId), [1064])) {
263
+                        if (in_array((int) @mysqli_errno($this->linkId), [1064])) {
264 264
                             $tries = 0;
265 265
                         }
266 266
                         break;
267 267
                     }
268 268
                 } catch (\mysqli_sql_exception $e) {
269
-                    if (in_array((int)$e->getCode(), [1213, 2006, 3101, 1180])) {
269
+                    if (in_array((int) $e->getCode(), [1213, 2006, 3101, 1180])) {
270 270
                         //error_log("got ".$e->getCode()." sql error fails {$fails}");
271 271
                         usleep(250000); // 0.25 second
272 272
                     } else {
273 273
                         error_log('Got mysqli_sql_exception code '.$e->getCode().' error '.$e->getMessage().' on query '.$queryString.' from '.$line.':'.$file);
274 274
                         $onlyRollback = false;
275
-                        if (in_array((int)@mysqli_errno($this->linkId), [1064])) {
275
+                        if (in_array((int) @mysqli_errno($this->linkId), [1064])) {
276 276
                             $tries = 0;
277 277
                         }
278 278
                         break;
Please login to merge, or discard this patch.