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