/
pdo_wrapper.db.class.php
370 lines (317 loc) · 9.61 KB
/
pdo_wrapper.db.class.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
<?php
/**
* Class PDOWrapper
*/
class PDOWrapper
{
private $dbh;
private $idFieldName = "id";
private $lastError = false;
/**
* Static method for creating PDOWrapper object with SQLITE connection
*
* @param string $dbFilePath Sqlite file path
* @return PDOWrapper
*/
public static function openSqlite( $dbFilePath )
{
return new PDOWrapper("sqlite:".$dbFilePath, "", "");
}
/**
* Static method for creating PDOWrapper object with MYSQL connection
*
* @param string $host Mysql host
* @param string $dbName Mysql database name
* @param string $username Mysql user name
* @param string $password Mysql password
* @param string $charset Connection charset
* @return PDOWrapper
*/
public static function openMysql($host, $dbName, $username, $password, $charset="")
{
$wrapper = new PDOWrapper("mysql:host=$host;dbname=$dbName", $username, $password);
if ($charset && !$wrapper->getLastError())
$wrapper->query("SET NAMES ?", array($charset));
return $wrapper;
}
/**
* Class constructor
*
* @param string $dsn Connection DSN
* @param string $username Connection user name
* @param string $password Connection password
*/
function __construct($dsn, $username, $password)
{
try
{
$this->lastError = false;
$this->dbh = new PDO($dsn, $username, $password);
$this->dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch (PDOException $e)
{
$this->error( $e->getMessage() );
}
}
/**
* Clears error variable
*/
private function clearError()
{
$this->lastError = false;
}
/**
* This method is called when an error occurs
*
* @param string $errorMsg Error description
*/
private function error($errorMsg="")
{
if ( $errorMsg )
{
$this->lastError = $errorMsg;
}
else
{
$info = $this->dbh->errorInfo();
if ( $info[1] )
$this->lastError = $info[2];
}
}
/**
* Set id field name for other methods with id parameter
*
* @param string $idFieldName ID field name
*/
public function setIdFieldName( $idFieldName )
{
if ( $idFieldName )
$this->idFieldName = $idFieldName;
}
/**
* Returns last error description
*
* @return bool|string Error description or false when no error
*/
public function getLastError()
{
return $this->lastError;
}
/**
* Execute SQL query
*
* @param string $sql SQL statement
* @param array $bind Bind parameters array
* @return bool|PDOStatement PDO statement or false when an error occurs
*/
public function query($sql, $bind=array())
{
$this->clearError();
try
{
$sth = $this->dbh->prepare( $sql );
$sth->execute( $bind );
}
catch (PDOException $e)
{
$sth = false;
$this->error( $e->getMessage() );
}
return $sth;
}
/**
* Insert a record to a table
*
* @param string $table Table name
* @param array $fieldAndValueList Associative array with the pairs: "field name" => value
* @return bool|string Last insert ID or false when an error occurs
*/
public function insertRecord($table, $fieldAndValueList)
{
$fields = "";
$placeholders = "";
$values = array();
foreach ($fieldAndValueList as $field => $value)
{
if ( $fields )
$fields .= ",";
$fields .= $field;
if ( $placeholders )
$placeholders .= ",";
$placeholders .= "?";
$values[] = $value;
}
$res = $this->query("INSERT INTO $table ($fields) VALUES ($placeholders)", $values);
if ( $res )
return $this->dbh->lastInsertId();
return false;
}
/**
* Update records for one table
*
* @param string $table Table name
* @param array $fieldAndValueList Associative array with the pairs: "field name" => value
* @param string $whereWithNonameParams Where string with positional placeholders
* @param array $whereData Bind parameters array for "where"
* @return bool Returns TRUE on success or FALSE on failure
*/
public function updateRecord($table, $fieldAndValueList, $whereWithNonameParams="", $whereData=array())
{
if ( $whereWithNonameParams )
$whereWithNonameParams = "WHERE ".$whereWithNonameParams;
$fields = "";
$values = array();
foreach ($fieldAndValueList as $field => $value)
{
if ( $fields )
$fields .= ",";
$fields .= $field."=?";
$values[] = $value;
}
$values = array_merge($values, $whereData);
$res = $this->query("UPDATE $table SET $fields $whereWithNonameParams", $values);
return $res ? true : false;
}
/**
* Update records for one table for one record with id=value
*
* @param string $table Table name
* @param array $fieldAndValueList Associative array with the pairs: "field name" => value
* @param mixed $id ID value
* @return bool Returns TRUE on success or FALSE on failure
*/
public function updateRecordWithId($table, $fieldAndValueList, $id)
{
return $this->updateRecord($table, $fieldAndValueList, '`'.$this->idFieldName.'`=?', array($id));
}
/**
* Delete records from table
*
* @param string $table Table name
* @param string $where Where string
* @param array $whereData Bind parameters array for "where"
* @return bool Returns TRUE on success or FALSE on failure
*/
public function deleteRecord($table, $where="", $whereData=array())
{
if ( $where )
$where = "WHERE ".$where;
$res = $this->query("DELETE FROM $table $where", $whereData);
return $res ? true : false;
}
/**
* Delete one record from table with id=value
*
* @param string $table Table name
* @param mixed $id ID value
* @return bool Returns TRUE on success or FALSE on failure
*/
public function deleteRecordWithId($table, $id)
{
return $this->deleteRecord($table, '`'.$this->idFieldName.'`=?', array($id));
}
/**
* Select records from a table and returns row(s) as 2D array
*
* @param string $sql SQL statement
* @param array $bind Bind parameters array
* @return array|bool Row(s) as 2D array or false when an error occurs
*/
public function selectRecords($sql, $bind=array())
{
$sth = $this->query($sql, $bind);
if ( !$sth )
return false;
try
{
$sth->setFetchMode( PDO::FETCH_ASSOC );
$res = $sth->fetchAll();
}
catch (PDOException $e)
{
$res = false;
$this->error( $e->getMessage() );
}
return $res;
}
/**
* Select first record from a table
*
* @param string $sql SQL statement
* @param array $bind Bind parameters array
* @return array|bool A result row or false when an error occurs
*/
public function selectFirstRecord($sql, $bind=array())
{
$sth = $this->query($sql, $bind);
if ( !$sth )
return false;
try
{
$sth->setFetchMode( PDO::FETCH_ASSOC );
$res = $sth->fetch();
}
catch (PDOException $e)
{
$res = false;
$this->error( $e->getMessage() );
}
return $res;
}
/**
* Select record from a table with id=value
*
* @param string $table Table name
* @param mixed $id ID value
* @return array|bool A result row or false when an error occurs
*/
public function selectRecordWithId($table, $id)
{
return $this->selectFirstRecord("SELECT * FROM $table WHERE `".$this->idFieldName."`=?", array($id));
}
/**
* Get number of rows
*
* @param string $table Table name
* @param string $where Where string
* @param array $whereData Bind parameters array for "where"
* @return bool|int Number of rows or false when an error occurs
*/
public function getRowCount($table, $where="", $whereData=array())
{
if ( $where )
$where = "WHERE ".$where;
$res = $this->selectFirstRecord("SELECT COUNT(*) AS num FROM $table $where", $whereData);
if ($res === false)
return false;
return intval( $res["num"] );
}
/**
* Initiates a transaction
*
* @return bool Returns TRUE on success or FALSE on failure
*/
public function beginTransaction()
{
return $this->dbh->beginTransaction();
}
/**
* Commits a transaction
*
* @return bool Returns TRUE on success or FALSE on failure
*/
public function endTransaction()
{
return $this->dbh->commit();
}
/**
* Rolls back a transaction
*
* @return bool Returns TRUE on success or FALSE on failure
*/
public function cancelTransaction()
{
return $this->dbh->rollBack();
}
}