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