Passed
Push — master ( 0eb506...d880a0 )
by Joe
02:52
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 2
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
15
/**
16
 * Db
17
 *
18
 * @access public
19
 */
20
class Db extends Generic implements Db_Interface {
21
	/* public: connection parameters */
22
	public $driver = 'mysql';
23
	public $Rows = [];
24
	/* public: this is an api revision, not a CVS revision. */
25
	public $type = 'pdo';
26
27
	/**
28
	 * 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 selectDb($database) {
34
		$dSN = "{$this->driver}:dbname={$database};host={$this->host}";
35
		if ($this->characterSet != '')
36
			$dSN .= ';charset='.$this->characterSet;
37
		$this->linkId = new \PDO($dSN, $this->user, $this->password);
38
	}
39
40
	/* public: connection management */
41
42
	/**
43
	 * Db::connect()
44
	 * @param string $database
45
	 * @param string $host
46
	 * @param string $user
47
	 * @param string $password
48
	 * @param string $driver
49
	 * @return bool|int|\PDO
50
	 */
51
	public function connect($database = '', $host = '', $user = '', $password = '', $driver = 'mysql') {
52
		/* Handle defaults */
53
		if ('' == $database)
54
			$database = $this->database;
55
		if ('' == $host)
56
			$host = $this->host;
57
		if ('' == $user)
58
			$user = $this->user;
59
		if ('' == $password)
60
			$password = $this->password;
61
		if ('' == $driver)
62
			$driver = $this->driver;
63
		/* establish connection, select database */
64
		$dSN = "$driver:dbname=$database;host=$host";
65
		if ($this->characterSet != '')
66
			$dSN .= ';charset='.$this->characterSet;
67
		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...
68
			try {
69
				$this->linkId = new \PDO($dSN, $user, $password);
70
			} catch (\PDOException $e) {
71
				$this->halt('Connection Failed '.$e->getMessage());
72
				return 0;
73
			}
74
		}
75
		return $this->linkId;
76
	}
77
78
	/* This only affects systems not using persistent connections */
79
80
	/**
81
	 * Db::disconnect()
82
	 * @return void
83
	 */
84
	public function disconnect() {
85
	}
86
87
	/* public: discard the query result */
88
89
	/**
90
	 * Db::free()
91
	 * @return void
92
	 */
93
	public function free() {
94
		//			@mysql_free_result($this->queryId);
95
		//			$this->queryId = 0;
96
	}
97
98
	/**
99
	 * Db::query()
100
	 *
101
	 *  Sends an SQL query to the database
102
	 *
103
	 * @param mixed $queryString
104
	 * @param string $line
105
	 * @param string $file
106
	 * @return mixed 0 if no query or query id handler, safe to ignore this return
107
	 */
108
	public function query($queryString, $line = '', $file = '') {
109
		/* No empty queries, please, since PHP4 chokes on them. */
110
		/* The empty query string is passed on from the constructor,
111
		* when calling the class without a query, e.g. in situations
112
		* like these: '$db = new db_Subclass;'
113
		*/
114
		if ($queryString == '')
115
			return 0;
116
		if (!$this->connect()) {
117
			return 0;
118
			/* we already complained in connect() about that. */
119
		}
120
		// New query, discard previous result.
121
		if ($this->queryId !== false)
0 ignored issues
show
introduced by
The condition $this->queryId !== false is always true.
Loading history...
122
			$this->free();
123
124
		if ($this->Debug)
125
			printf("Debug: query = %s<br>\n", $queryString);
126
		if (isset($GLOBALS['log_queries']) && $GLOBALS['log_queries'] !== false)
127
			$this->log($queryString, $line, $file);
128
129
		$this->queryId = $this->linkId->prepare($queryString);
130
		$success = $this->queryId->execute();
131
		$this->Rows = $this->queryId->fetchAll();
132
		$this->log("PDO Query $queryString (S:$success) - ".count($this->Rows).' Rows', __LINE__, __FILE__);
133
		$this->Row = 0;
134
		if ($success === false) {
135
			$this->emailError($queryString, json_encode($this->queryId->errorInfo(), JSON_PRETTY_PRINT), $line, $file);
136
		}
137
138
		// Will return nada if it fails. That's fine.
139
		return $this->queryId;
140
	}
141
142
	/* public: walk result set */
143
144
	/**
145
	 * Db::next_record()
146
	 * @param mixed $resultType
147
	 * @return bool
148
	 */
149
	public function next_record($resultType = MYSQL_ASSOC) {
0 ignored issues
show
introduced by
The constant MYSQL_ASSOC has been deprecated: 5.5 ( Ignorable by Annotation )

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

149
	public function next_record($resultType = /** @scrutinizer ignore-deprecated */ MYSQL_ASSOC) {
Loading history...
150
		// PDO result types so far seem to be +1
151
		++$resultType;
152
		if (!$this->queryId) {
153
			$this->halt('next_record called with no query pending.');
154
			return 0;
155
		}
156
157
		++$this->Row;
158
		$this->Record = $this->Rows[$this->Row];
159
160
		$stat = is_array($this->Record);
161
		if (!$stat && $this->autoFree)
162
			$this->free();
163
		return $stat;
164
	}
165
166
	/* public: position in result set */
167
168
	/**
169
	 * Db::seek()
170
	 * @param integer $pos
171
	 * @return int
172
	 */
173
	public function seek($pos = 0) {
174
		if (isset($this->Rows[$pos])) {
175
			$this->Row = $pos;
176
		} else {
177
			$this->halt("seek($pos) failed: result has ".count($this->Rows).' rows');
178
			/* half assed attempt to save the day,
179
			* but do not consider this documented or even
180
			* desirable behaviour.
181
			*/
182
			return 0;
183
		}
184
		return 1;
185
	}
186
187
	/**
188
	 * Initiates a transaction
189
	 * @return bool
190
	 */
191
	public function transactionBegin() {
192
		return $this->linkId->beginTransaction();
193
	}
194
195
	/**
196
	 * Commits a transaction
197
	 * @return bool
198
	 */
199
	public function transactionCommit() {
200
		return $this->linkId->commit();
201
	}
202
203
	/**
204
	 * Rolls back a transaction
205
	 * @return bool
206
	 */
207
	public function transactionAbort() {
208
		return $this->linkId->rollBack();
209
	}
210
211
	/**
212
	 * Db::getLastInsertId()
213
	 * @param mixed $table
214
	 * @param mixed $field
215
	 * @return int
216
	 */
217
	public function getLastInsertId($table, $field) {
218
		if (!isset($table) || $table == '' || !isset($field) || $field == '')
219
			return -1;
220
		return $this->linkId->lastInsertId();
221
	}
222
223
	/* public: table locking */
224
225
	/**
226
	 * Db::lock()
227
	 * @param mixed  $table
228
	 * @param string $mode
229
	 * @return void
230
	 */
231
	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

231
	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

231
	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...
232
		/*			$this->connect();
233
234
		* $query = "lock tables ";
235
		* if (is_array($table))
236
		* {
237
		* foreach ($table as $key => $value)
238
		* {
239
		* if ($key == "read" && $key!=0)
240
		* {
241
		* $query .= "$value read, ";
242
		* }
243
		* else
244
		* {
245
		* $query .= "$value $mode, ";
246
		* }
247
		* }
248
		* $query = mb_substr($query,0,-2);
249
		* }
250
		* else
251
		* {
252
		* $query .= "$table $mode";
253
		* }
254
		* $res = @mysql_query($query, $this->linkId);
255
		* if (!$res)
256
		* {
257
		* $this->halt("lock($table, $mode) failed.");
258
		* return 0;
259
		* }
260
		* return $res;
261
		*/
262
	}
263
264
	/**
265
	 * Db::unlock()
266
	 * @return void
267
	 */
268
	public function unlock() {
269
		/*			$this->connect();
270
271
		* $res = @mysql_query("unlock tables");
272
		* if (!$res)
273
		* {
274
		* $this->halt("unlock() failed.");
275
		* return 0;
276
		* }
277
		* return $res;
278
		*/
279
	}
280
281
	/* public: evaluate the result (size, width) */
282
283
	/**
284
	 * Db::affectedRows()
285
	 *
286
	 * @return mixed
287
	 */
288
	public function affectedRows() {
289
		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

289
		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...
290
	}
291
292
	/**
293
	 * Db::num_rows()
294
	 * @return int
295
	 */
296
	public function num_rows() {
297
		return count($this->Rows);
298
	}
299
300
	/**
301
	 * Db::num_fields()
302
	 * @return int
303
	 */
304
	public function num_fields() {
305
		$keys = array_keys($this->Rows);
306
		return count($this->Rows[$keys[0]]);
307
	}
308
309
	/**
310
	 * @param mixed $msg
311
	 * @param string $line
312
	 * @param string $file
313
	 * @return mixed|void
314
	 */
315
	public function haltmsg($msg, $line = '', $file = '') {
316
		$this->log("Database error: $msg", $line, $file, 'error');
317
		if ($this->Errno != '0' || $this->Error != '()')
318
			$this->log('PDO MySQL Error: '.json_encode($this->linkId->errorInfo()), $line, $file, 'error');
319
		$this->logBackTrace($msg, $line, $file);
320
	}
321
322
	/**
323
	 * Db::tableNames()
324
	 *
325
	 * @return array
326
	 */
327
	public function tableNames() {
328
		$return = [];
329
		$this->query('SHOW TABLES');
330
		foreach ($this->Rows as $i => $info) {
331
			$return[$i]['table_name'] = $info[0];
332
			$return[$i]['tablespace_name'] = $this->database;
333
			$return[$i]['database'] = $this->database;
334
		}
335
		return $return;
336
	}
337
}
338