-
Notifications
You must be signed in to change notification settings - Fork 0
/
DBWrapper.php
335 lines (272 loc) · 12.1 KB
/
DBWrapper.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
<?php
require_once('DBConfig.php');
class DBWrapper {
//PDO Connection Object
private $conn;
//Constructor
public function __construct($isNonBufferedQuery = false) {
try {
if($isNonBufferedQuery){
//Connecting to the database host and database using the credentials
$this->conn = new PDO('mysql:host='.DB_HOST.';dbname='.DB_NAME.'', DB_USER, DB_PASSWORD, array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8mb4 COLLATE utf8mb4_unicode_ci", PDO::MYSQL_ATTR_USE_BUFFERED_QUERY => false));
}
else {
//Connecting to the database host and database using the credentials
$this->conn = new PDO('mysql:host='.DB_HOST.';dbname='.DB_NAME.'', DB_USER, DB_PASSWORD, array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8mb4 COLLATE utf8mb4_unicode_ci"));
}
$this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e) {
throw new Exception($e->getMessage());
}
}
public function beginTransaction() {
$this->conn->beginTransaction();
}
public function commit() {
$this->conn->commit();
}
public function rollBack() {
$this->conn->rollBack();
}
//Function to get the primary key column name from a table
public function getPrimaryKey($table) {
try {
$stmt = $this->conn->prepare("SHOW KEYS FROM $table WHERE Key_name = 'PRIMARY'");
$stmt->execute();
$array = $stmt->fetchAll(PDO::FETCH_ASSOC);
return $array[0]['Column_name'];
}
catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
}
//Function to get a parameuterized PDO Query String
public function getPDOParameuterizedSelectQuery($table, $fields = '*' , $conditionParams, $groupBy = null, $limit = '', $sort=null, $fetchStyle = PDO::FETCH_ASSOC, $isIterationEnabled = false) {
$query = "SELECT $fields FROM $table";
//Checking if any conditions are there for the 'Where' Clause
if(count($conditionParams) > 0) {
$query.= " WHERE ";
//Fetching and appending the names of parameters and their parameuterized names in the where clause
//in the format "where id=:id and name=:name" etc
$keys = array_keys($conditionParams);
for($i=0; $i<count($keys); $i++) {
$query.= $keys[$i];
$query.= ' = ';
$query.= ($i==count($keys)-1)? ':'.$keys[$i] : ':'.$keys[$i].' and ';
}
}
//checking if the result set needs to be grouped
if(isset($groupBy)) {
$query.= " GROUP BY $groupBy ";
}
//checking if the result needs to be sorted
if(isset($sort)) {
$query.= " order by $sort ";
}
//Applying the limit clause parameter
$query.= "$limit";
//checking if iteration needs to be enabled
if($isIterationEnabled) {
$stmt = $this->conn->prepare($query, [\PDO::ATTR_CURSOR => \PDO::CURSOR_SCROLL]);
}
else {
$stmt = $this->conn->prepare($query);
}
//Binding the condition parameters with their walues
if(count($conditionParams) > 0) {
$keys = array_keys($conditionParams);
for($i=0; $i<count($keys); $i++) {
$stmt->bindParam(':'.$keys[$i], $conditionParams[$keys[$i]]);
}
}
//returning object of type PDO Statement
return $stmt;
}
//Function to get records from database
public function select($table, $fields = '*' , $conditionParams, $groupBy = null, $limit = '', $sort=null, $fetchStyle = PDO::FETCH_ASSOC, $isIterationEnabled = false) { //fetchArgs, etc
//Gets the parameteurized PDO String
$stmt = $this->getPDOParameuterizedSelectQuery($table, $fields, $conditionParams, $groupBy, $limit, $sort, $fetchStyle, $isIterationEnabled);
$stmt->execute();
if($isIterationEnabled) {
//return the statement object in this case. The statement object can be used for iterating the result set in the caller.
return $stmt;
}
else {
$result = $stmt->fetchAll($fetchStyle);
//Return the result object
return $result;
}
}
//Function to insert row in table $table with parameters from $params
public function insert($table, $params, $insertIgnore = false) {
$query = '';
//checking if insert ignore is enabled
if($insertIgnore) {
$query = "INSERT IGNORE INTO $table(";
}
else {
$query = "INSERT INTO $table(";
}
//Fetching and appending the names of parameters
//in the format "insert into table(name,description,parent_id)
$keys = array_keys($params);
for($i=0; $i<count($keys); $i++) {
$query.= ($i==count($keys)-1)? $keys[$i] : $keys[$i].',';
}
//Fetching and appending the parameuterzied names of parameters
//in the format "values(:name,:description,:parent_id)"
$query.=") VALUES (";
for($i=0; $i<count($keys); $i++) {
$query.= ($i==count($keys)-1)? ':'.$keys[$i] : ':'.$keys[$i].',';
}
$query.=")";
try {
$stmt = $this->conn->prepare($query);
//Binding the parameters to their values
for($i=0; $i<count($keys); $i++) {
$stmt->bindParam(':'.$keys[$i], $params[$keys[$i]]);
}
//Executing the prepared statement
$stmt->execute();
//Returning the last inserted id
return $this->conn->lastInsertId();
}
catch(Exception $e) {
throw new Exception($e->getMessage());
}
}
//Function to update a record in $table, set updated data as in $updateParams, for the records matching $conditionsParams
public function update($table, $updateParams, $conditionParams)
{
$query = "UPDATE $table SET ";
//Fetching and appending the names of update parameters and their parameuterized names in the where clause
//in the format "set id=:id, name=:name" etc
$keys = array_keys($updateParams);
for($i=0; $i<count($keys); $i++) {
$query.= $keys[$i];
$query.= ' = ';
$query.= ($i==count($keys)-1)? ':'.$keys[$i] : ':'.$keys[$i].', ';
}
$query.= " where ";
//Fetching and appending the names of condition parameters and their parameuterized names in the where clause
//in the format "where id=:id and description=:description" etc
$conditionKeys = array_keys($conditionParams);
for($i=0; $i<count($conditionKeys); $i++) {
$query.= $conditionKeys[$i];
$query.= ' = ';
$query.= ($i==count($conditionKeys)-1)? ':D'.$conditionKeys[$i] : ':D'.$conditionKeys[$i].' and ';
}
try {
$stmt = $this->conn->prepare($query);
//Binding the Update parameters to their values
for($i=0; $i<count($keys); $i++) {
$stmt->bindParam(':'.$keys[$i], $updateParams[$keys[$i]]);
}
//Binding the Condition params to their values
for($i=0; $i<count($conditionKeys); $i++) {
$stmt->bindParam(':D'.$conditionKeys[$i], $conditionParams[$conditionKeys[$i]]);
}
//Executing the prepared statement
$stmt->execute();
//Returning the number of rows affected
return $stmt->rowCount();
}
catch(Exception $e) {
throw new Exception($e->getMessage());
}
}
//Function to delete a record from table $table which matches $conditionParams
public function delete($table, $conditionParams)
{
$query = "DELETE FROM $table";
//Checking if any conditions are there for the 'Where' Clause
if(count($conditionParams)>0) {
$query.= " WHERE ";
$keys = array_keys($conditionParams);
//Fetching and appending the names of parameters and their parameuterized names in the where clause
//in the format "where id=:id and name=:name" etc
for($i=0; $i<count($keys); $i++)
{
$query.= $keys[$i];
$query.= ' = ';
$query.= ($i==count($keys)-1)? ':'.$keys[$i] : ':'.$keys[$i].' and ';
}
}
try {
$stmt = $this->conn->prepare($query);
if(count($conditionParams)>0) {
for($i=0; $i<count($keys); $i++) {
//Binding the query paramaters to their values
$stmt->bindParam(':'.$keys[$i], $conditionParams[$keys[$i]]);
}
}
//Executing the prepared statement
$stmt->execute();
//Returning the number of rows affected
return $stmt->rowCount();
}
catch(Exception $e) {
throw new Exception($e->getMessage());
}
}
//Function to execute a select(can be used for joins) query with manually binded parameters
public function manualBindSelect($query, $params = Array(), $values = Array(), $paramDataTypes = Array(), $fetchStyle = PDO::FETCH_ASSOC, $isIterationEnabled = false) {
if($isIterationEnabled) {
$stmt = $this->conn->prepare($query, [\PDO::ATTR_CURSOR => \PDO::CURSOR_SCROLL]);
}
else {
$stmt = $this->conn->prepare($query);
}
//Binding the Update parameters to their values
for($i=0; $i<count($params); $i++) {
if($paramDataTypes[$i] == 'int') {
$stmt->bindValue(':'.$params[$i], $values[$i], PDO::PARAM_INT);
}
if($paramDataTypes[$i] == 'str') {
$stmt->bindValue(':'.$params[$i], $values[$i], PDO::PARAM_STR);
}
if($paramDataTypes[$i] == 'bool') {
$stmt->bindValue(':'.$params[$i], $values[$i], PDO::PARAM_BOOL);
}
if($paramDataTypes[$i] == 'null') {
$stmt->bindValue(':'.$params[$i], $values[$i], PDO::PARAM_NULL);
}
}
//Executing the prepared statement
$stmt->execute();
if($isIterationEnabled) {
//return the statement object in this case. The statement object can be used for iterating the result set in the caller.
return $stmt;
}
else {
$result = $stmt->fetchAll($fetchStyle);
//Returning the result object
return $result;
}
}
//Function to execute an update query(with joins for example) with manually binded paramters
public function manualBindUpdate($query, $params = Array(), $values = Array(), $paramDataTypes = Array()) {
$stmt = $this->conn->prepare($query);
//Binding the Update parameters to their values
for($i=0; $i<count($params); $i++) {
if($paramDataTypes[$i] == 'int') {
$stmt->bindValue(':'.$params[$i], $values[$i], PDO::PARAM_INT);
}
if($paramDataTypes[$i] == 'str') {
$stmt->bindValue(':'.$params[$i], $values[$i], PDO::PARAM_STR);
}
if($paramDataTypes[$i] == 'bool') {
$stmt->bindValue(':'.$params[$i], $values[$i], PDO::PARAM_BOOL);
}
if($paramDataTypes[$i] == 'null') {
$stmt->bindValue(':'.$params[$i], $values[$i], PDO::PARAM_NULL);
}
}
//Executing the prepared statement
$stmt->execute();
//Returning the number of rows affected
return $stmt->rowCount();
}
}
?>