-
Notifications
You must be signed in to change notification settings - Fork 0
/
DAO.php
312 lines (254 loc) · 8.76 KB
/
DAO.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
<?php
require_once './configuration.php';
/**
* Description of DAO
*
* @author Lucas
*/
class DAO
{
/** DB properties */
public $dbDriver, // DataBase Driver, like MySQL, ProstgreSQL, etc
$host, // Hostname
$dbName, // Name
$user, // User
$password, // Password
$charset, // Charset
$debug, // Show All Errors
$pdo = null, // Connection Type
$error = null, // Configures Error
$lastId = null; // Last Inserted id
/**
* Class Constructor
* @access public
* @param string $host
* @param string $dbName
* @param string $password
* @param string $user
* @param string $charset
* @param string $debug
*/
public function __construct($dbDriver = false, $host = false, $dbName = false, $user = false, $password = false, $charset = false, $debug = false)
{
// Two way of connect
$this->dbDriver = DB_DRIVER;
$this->host = DB_HOSTNAME;
$this->dbName = DB_NAME;
$this->user = DB_USER;
$this->password = DB_PASSWORD;
$this->charset = DB_CHARSET;
$this->debug = DEBUG;
// Connects
$this->connect();
}
/**
* Creates the connection with database
* @final
* @access protected
*/
final protected function connect()
{
/* PDO Details */
$pdo_details = $this->dbDriver.":host={$this->host};";
$pdo_details .= "dbname={$this->dbName};";
$pdo_details .= "charset={$this->charset};";
// Try to connect
try {
$this->pdo = new PDO($pdo_details, $this->user, $this->password);
// Verify if needs debug
if ($this->debug === true) {
// Configures PDO ERROR MODE
$this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
}
// We do not need these properties in memory anymores
unset($this->host);
unset($this->dbName);
unset($this->password);
unset($this->user);
unset($this->charset);
} catch (PDOException $e) {
// Verify if needs debug again
if ($this->debug === true) {
// Showing error message
echo "Error: " . $e->getMessage();
}
// Kills the script
die();
}
}
public function selectAll($sTable, $sWhere = false)
{
// Prepares to execute
$sStatement = 'SELECT * FROM ' . $sTable . ' ';
if ($sWhere !== false) {
$sStatement .= 'WHERE ' . $sWhere;
}
$query = $this->pdo->prepare($sStatement);
$result = $query->execute();
// Verifies if the query was right made
if ($result) {
// Returns query
return $query->fetchAll(PDO::FETCH_ASSOC);
} else {
// Instances error
$error = $query->errorInfo();
$this->error = $error[2];
// Retorns false because the error(s)
return false;
}
}
/**
* Querys the DataBase
* @access public
* @return object|bool Returns the query in case of true, else returns false
*/
public function query($sStatement, $aArrayData = null)
{
// Prepares to execute
$query = $this->pdo->prepare($sStatement);
$checkExecution = $query->execute($aArrayData);
// Verifies if the query was right made
if ($checkExecution) {
// Returns query
return $query;
} else {
// Instances error
$error = $query->errorInfo();
$this->error = $error[2];
// Retorns false because the error(s)
return false;
}
}
/**
* Insert values in database
* @access public
* @param string $table table name
* @param array Hidden and unlimited params: keys and values to insert in column => value style
* @return object|bool Returns the query itself or false in case of can
*/
public function insert($table)
{
// Start cols list
$aCols = array();
// Configura o valor inicial do modelo
$sPlaceHolders = '(';
// Start the array values
$aValues = array();
// O $j will assegura que colunas serão configuradas apenas uma vez
$j = 1;
// Get all extra function arguments
$aArgs = func_get_args();
// É preciso enviar pelo menos um array de chaves e valores
if (!isset($aArgs[1]) || !is_array($aArgs[1])) {
return false;
}
// Iterates all function args
for ($i = 1; $i < count($aArgs); $i++) {
// Get the keys as columns and their respective values
foreach ($aArgs[$i] as $col => $val) {
// The first iteration starts the columns
if ($i === 1) {
$aCols[] = $col;
}
if ($j != $i) {
// Configures values divisors
$sPlaceHolders .= '), (';
}
// Add placeholder to replace
$sPlaceHolders .= '?, ';
// Creates the list of columns values
$aValues[] = $val;
$j = $i;
}
// Remove extra placeholder's characters
$sPlaceHolders = substr($sPlaceHolders, 0, strlen($sPlaceHolders) - 2);
}
// Divide columns by commas
$aCols = implode(', ', $aCols);
// Create statement expression to execute
$statement = "INSERT INTO $table ($aCols) VALUES $sPlaceHolders) ";
// insert values
$insert = $this->query($statement, $aValues);
// Verifies if insert was succeed
if ($insert) {
// Verifies if we have last inserted Id
if (method_exists($this->pdo, 'lastInsertId') && $this->pdo->lastInsertId()
) {
// instances last Id
$this->lastId = $this->pdo->lastInsertId();
}
// Returns insert query response
return $insert;
}
}
/**
* Updates field value
* @access protected
* @param string $sTable Table name
* @param string $sWhereField WHERE $sWhereField = $sWhereFieldValue
* @param string $sWhereFieldValue WHERE $sWhereField = $sWhereFieldValue
* @param array $aValues Array with new values
* @return object|bool Returns the query or false
*/
public function update($sTable, $sWhereField, $sWhereFieldValue, $aValues) {
// Need all params
if (empty($sTable) || empty($sWhereField) || empty($sWhereFieldValue) || !is_array($aValues)) {
return false;
}
// Begin statement
$sStatement = " UPDATE $sTable SET ";
// start array with values
$aSet = array();
// Start of "Where"
$sWhere = " WHERE `$sWhereField` = ? ";
// Configures columns to update
foreach ($aValues as $column => $value) {
$aSet[] = " $column = ?";
}
// Separete columns by commas
$aSet = implode(', ', $aSet);
// Concats statement
$sStatement .= $aSet . $sWhere;
// Creates list of values to search
$aValues[] = $sWhereFieldValue;
// Guarantee only numbers in keys and re-organizes array
$aValues = array_values($aValues);
// Updates
$bUpdate = $this->query($sStatement, $aValues);
// Verifica se a consulta está OK
if ($bUpdate) {
// Retorns query
return $bUpdate;
}
}
/**
* Delets a row in database
* @access protected
* @param string $sTable Nome da tabela
* @param string $sWhereField WHERE $where_field = $where_field_value
* @param string $sWhereFieldValue WHERE $where_field = $where_field_value
* @return object|bool Retorna a consulta ou falso
*/
public function delete($sTable, $sWhereField, $sWhereFieldValue)
{
// Need to send all params
if (empty($sTable) || empty($sWhereField) || empty($sWhereFieldValue)) {
return false;
}
// Begins statement
$sStatement = " DELETE FROM `$sTable` ";
// Configures as WHERE field = value
$sWhere = " WHERE $sWhereField = $sWhereFieldValue ";
// Concats all
$sStatement .= $sWhere;
// Value to search and delete
// $aValue = array($sWhereFieldValue);
// delete
$bDelete = $this->query($sStatement);
// Verifica se a consulta está OK
if ($bDelete) {
// Retorna a consulta
return $bDelete;
}
}
}