Test Failed
Push — master ( c97961...600310 )
by Joe
02:40
created

Db::useDb()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 2
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 1
dl 0
loc 2
ccs 0
cts 0
cp 0
crap 2
rs 10
c 0
b 0
f 0
1
<?php
2
/**
3
 * PDO SQL Related Functionality
4
 * @author Joe Huss <[email protected]>
5
 * @copyright 2018
6
 * @package MyAdmin
7
 * @category SQL
8
 */
9
10
namespace MyDb\Pdo;
11
12
use \MyDb\Generic;
13
use \MyDb\Db_Interface;
14
use \PDO;
15
16
/**
17
 * Db
18
 *
19
 * @access public
20
 */
21
class Db extends Generic implements Db_Interface {
22
	/* public: connection parameters */
23
	public $driver = 'mysql';
24
	public $Rows = [];
25
	/* public: this is an api revision, not a CVS revision. */
26
	public $type = 'pdo';
27
28
	/**
29
	 * changes the database we are working with.
30
	 *
31
	 * @param string $database the name of the database to use
32
	 * @return void
33
	 */
34
	public function selectDb($database) {
35
		$dSN = "{$this->driver}:dbname={$database};host={$this->host}";
36
		if ($this->characterSet != '')
37
			$dSN .= ';charset='.$this->characterSet;
38
		$this->linkId = new PDO($dSN, $this->user, $this->password);
39
		$this->database = $database;
40
	}
41
42
43
	/**
44
	 * alias function of select_db, changes the database we are working with.
45
	 *
46
	 * @param string $database the name of the database to use
47
	 * @return void
48
	 */
49
	public function useDb($database) {
50
		$this->selectDb($database);
51
	}
52
	
53
	/* public: connection management */
54
55
	/**
56
	 * Db::connect()
57
	 * @param string $database
58
	 * @param string $host
59
	 * @param string $user
60
	 * @param string $password
61
	 * @param string $driver
62
	 * @return bool|int|PDO
63
	 */
64
	public function connect($database = '', $host = '', $user = '', $password = '', $driver = 'mysql') {
65
		/* Handle defaults */
66
		if ('' == $database)
67
			$database = $this->database;
68
		if ('' == $host)
69
			$host = $this->host;
70
		if ('' == $user)
71
			$user = $this->user;
72
		if ('' == $password)
73
			$password = $this->password;
74
		if ('' == $driver)
75
			$driver = $this->driver;
76
		/* establish connection, select database */
77
		$dSN = "{$driver}:dbname={$database};host={$host}";
78
		if ($this->characterSet != '')
79
			$dSN .= ';charset='.$this->characterSet;
80
		if ($this->linkId === false) {
0 ignored issues
show
introduced by
The condition $this->linkId is always false. If $this->linkId can have other possible types, add them to src/Generic.php:48
Loading history...
81
			try {
82
				$this->linkId = new PDO($dSN, $user, $password);
83
			} catch (\PDOException $e) {
84
				$this->halt('Connection Failed '.$e->getMessage());
85
				return 0;
86
			}
87
		}
88
		return $this->linkId;
89
	}
90
91
	/* This only affects systems not using persistent connections */
92
93
	/**
94
	 * Db::disconnect()
95
	 * @return void
96
	 */
97
	public function disconnect() {
98
	}
99
100
	/* public: discard the query result */
101
102
	/**
103
	 * Db::free()
104
	 * @return void
105
	 */
106
	public function free() {
107
		//			@mysql_free_result($this->queryId);
108
		//			$this->queryId = 0;
109
	}
110
111
	/**
112
	 * Db::query()
113
	 *
114
	 *  Sends an SQL query to the database
115
	 *
116
	 * @param mixed $queryString
117
	 * @param string $line
118
	 * @param string $file
119
	 * @return mixed 0 if no query or query id handler, safe to ignore this return
120
	 */
121
	public function query($queryString, $line = '', $file = '') {
122
		/* No empty queries, please, since PHP4 chokes on them. */
123
		/* The empty query string is passed on from the constructor,
124
		* when calling the class without a query, e.g. in situations
125
		* like these: '$db = new db_Subclass;'
126
		*/
127
		if ($queryString == '')
128
			return 0;
129
		if (!$this->connect()) {
130
			return 0;
131
			/* we already complained in connect() about that. */
132
		}
133
		// New query, discard previous result.
134
		if ($this->queryId !== false)
0 ignored issues
show
introduced by
The condition $this->queryId !== false is always true.
Loading history...
135
			$this->free();
136
137
		if ($this->Debug)
138
			printf("Debug: query = %s<br>\n", $queryString);
139
		if (isset($GLOBALS['log_queries']) && $GLOBALS['log_queries'] !== false)
140
			$this->log($queryString, $line, $file);
141
142
		$this->queryId = $this->linkId->prepare($queryString);
143
		$success = $this->queryId->execute();
144
		$this->Rows = $this->queryId->fetchAll();
145
		//$this->log("PDO Query $queryString (S:$success) - ".count($this->Rows).' Rows', __LINE__, __FILE__);
146
		$this->Row = -1;
147
		if ($success === false) {
148
			$this->emailError($queryString, json_encode($this->queryId->errorInfo(), JSON_PRETTY_PRINT), $line, $file);
149
		}
150
151
		// Will return nada if it fails. That's fine.
152
		return $this->queryId;
153
	}
154
155
	/* public: walk result set */
156
157
	/**
158
	 * Db::next_record()
159
	 * @param mixed $resultType
160
	 * @return bool
161
	 */
162
	public function next_record($resultType = MYSQLI_ASSOC) {
163
		// PDO result types so far seem to be +1
164
		++$resultType;
165
		if (!$this->queryId) {
166
			$this->halt('next_record called with no query pending.');
167
			return 0;
168
		}
169
170
		++$this->Row;
171
		$this->Record = $this->Rows[$this->Row];
172
173
		$stat = is_array($this->Record);
174
		if (!$stat && $this->autoFree)
175
			$this->free();
176
		return $stat;
177
	}
178
179
	/* public: position in result set */
180
181
	/**
182
	 * Db::seek()
183
	 * @param integer $pos
184
	 * @return int
185
	 */
186
	public function seek($pos = 0) {
187
		if (isset($this->Rows[$pos])) {
188
			$this->Row = $pos;
189
		} else {
190
			$this->halt("seek($pos) failed: result has ".count($this->Rows).' rows');
191
			/* half assed attempt to save the day,
192
			* but do not consider this documented or even
193
			* desirable behaviour.
194
			*/
195
			return 0;
196
		}
197
		return 1;
198
	}
199
200
	/**
201
	 * Initiates a transaction
202
	 * @return bool
203
	 */
204
	public function transactionBegin() {
205
		return $this->linkId->beginTransaction();
206
	}
207
208
	/**
209
	 * Commits a transaction
210
	 * @return bool
211
	 */
212
	public function transactionCommit() {
213
		return $this->linkId->commit();
214
	}
215
216
	/**
217
	 * Rolls back a transaction
218
	 * @return bool
219
	 */
220
	public function transactionAbort() {
221
		return $this->linkId->rollBack();
222
	}
223
224
	/**
225
	 * Db::getLastInsertId()
226
	 * @param mixed $table
227
	 * @param mixed $field
228
	 * @return int
229
	 */
230
	public function getLastInsertId($table, $field) {
231
		if (!isset($table) || $table == '' || !isset($field) || $field == '')
232
			return -1;
233
		return $this->linkId->lastInsertId();
234
	}
235
236
	/* public: table locking */
237
238
	/**
239
	 * Db::lock()
240
	 * @param mixed  $table
241
	 * @param string $mode
242
	 * @return void
243
	 */
244
	public function lock($table, $mode = 'write') {
0 ignored issues
show
Unused Code introduced by
The parameter $mode is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

244
	public function lock($table, /** @scrutinizer ignore-unused */ $mode = 'write') {

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Unused Code introduced by
The parameter $table is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

244
	public function lock(/** @scrutinizer ignore-unused */ $table, $mode = 'write') {

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
245
		/*			$this->connect();
246
247
		* $query = "lock tables ";
248
		* if (is_array($table))
249
		* {
250
		* foreach ($table as $key => $value)
251
		* {
252
		* if ($key == "read" && $key!=0)
253
		* {
254
		* $query .= "$value read, ";
255
		* }
256
		* else
257
		* {
258
		* $query .= "$value $mode, ";
259
		* }
260
		* }
261
		* $query = mb_substr($query,0,-2);
262
		* }
263
		* else
264
		* {
265
		* $query .= "$table $mode";
266
		* }
267
		* $res = @mysql_query($query, $this->linkId);
268
		* if (!$res)
269
		* {
270
		* $this->halt("lock($table, $mode) failed.");
271
		* return 0;
272
		* }
273
		* return $res;
274
		*/
275
	}
276
277
	/**
278
	 * Db::unlock()
279
	 * @return void
280
	 */
281
	public function unlock() {
282
		/*			$this->connect();
283
284
		* $res = @mysql_query("unlock tables");
285
		* if (!$res)
286
		* {
287
		* $this->halt("unlock() failed.");
288
		* return 0;
289
		* }
290
		* return $res;
291
		*/
292
	}
293
294
	/* public: evaluate the result (size, width) */
295
296
	/**
297
	 * Db::affectedRows()
298
	 *
299
	 * @return mixed
300
	 */
301
	public function affectedRows() {
302
		return @$this->queryId->rowCount();
0 ignored issues
show
Bug introduced by
The method rowCount() does not exist on integer. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

302
		return @$this->queryId->/** @scrutinizer ignore-call */ rowCount();

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
303
	}
304
305
	/**
306
	 * Db::num_rows()
307
	 * @return int
308
	 */
309
	public function num_rows() {
310
		return count($this->Rows);
311
	}
312
313
	/**
314
	 * Db::num_fields()
315
	 * @return int
316
	 */
317
	public function num_fields() {
318
		$keys = array_keys($this->Rows);
319
		return count($this->Rows[$keys[0]]);
320
	}
321
322
	/**
323
	 * @param mixed $msg
324
	 * @param string $line
325
	 * @param string $file
326
	 * @return mixed|void
327
	 */
328
	public function haltmsg($msg, $line = '', $file = '') {
329
		$this->log("Database error: $msg", $line, $file, 'error');
330
		if ($this->Errno != '0' || $this->Error != '()')
331
			$this->log('PDO MySQL Error: '.json_encode($this->linkId->errorInfo()), $line, $file, 'error');
332
		$this->logBackTrace($msg, $line, $file);
333
	}
334
335
	/**
336
	 * Db::tableNames()
337
	 *
338
	 * @return array
339
	 */
340
	public function tableNames() {
341
		$return = [];
342
		$this->query('SHOW TABLES');
343
		foreach ($this->Rows as $i => $info) {
344
			$return[$i]['table_name'] = $info[0];
345
			$return[$i]['tablespace_name'] = $this->database;
346
			$return[$i]['database'] = $this->database;
347
		}
348
		return $return;
349
	}
350
}
351