-
Notifications
You must be signed in to change notification settings - Fork 2
/
mysql.class.php
381 lines (354 loc) · 11.9 KB
/
mysql.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
371
372
373
374
375
376
377
378
379
380
381
<?php
/**
* Simple Mysql class using PDO
*
* @package LMSQL
* @author Arash Soleimani <[email protected]>
* @link https://github.com/leomoon-studios/LMSQL
* @license https://opensource.org/licenses/MIT - The MIT License
* @version 1.2
*
*/
class LMSQL {
private $connectionInfo = array();
private $mypdo = null;
public $sqlQuery = "";
public $errorMessage = null;
/**
* DB Constructor
*
* @param string $host
* @param string $user
* @param string $db
* @param bool $autoConnect
* @param string $charset
*
* @example
* <code>
* $mysql = new LMSQL('localhost', 'root', '123456', 'mydatabase', true);
* </code>
*
*/
function __construct($host, $user, $pass, $db, $autoConnect=false, $charset = 'utf8') {
$this->connectionInfo = array('host'=>$host, 'user'=>$user, 'pass'=>$pass, 'db'=>$db, 'charset'=>$charset);
if($autoConnect){
$this->connect();
}
}
/**
* Connect to MySQL
*/
public function connect(){
try {
$this->mypdo = new PDO("mysql:host=".$this->connectionInfo['host'].";dbname=".$this->connectionInfo['db'].";charset=".$this->connectionInfo['charset'], $this->connectionInfo['user'], $this->connectionInfo['pass']);
$this->mypdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
} catch (PDOException $e) {
$this->errorMessage = "Connection failed: " . $e->getMessage();
}
}
/**
* Get data from table with where clause, limit, order and custom index
*
* @param array $queryInfo (
* 'table'=>'Table Name',
* 'fields'=>'fields', // - (optional)
* 'where'=>['id' => 1, 'name'=>'Arash'], // or "id = 1 AND name = 'Arash'" - (optional)
* 'order'=>'id DESC', // - (optional)
* 'limit'=>'10', // - (optional)
* 'index'=>['column'=>'type', 'multi'=>true], // - (optional)
* 'sql'=>'SELECT * FROM news' // - (optional)
* );
*
* @return array
*/
public function select($queryInfo){
$sql = $this->buildQuery('select', $queryInfo);
$query = $this->query($sql);
$result = $query->fetchAll();
if($result && isset($queryInfo['index'])){
foreach($result as $value){
if(isset($queryInfo['index']['multi'])){
$data[$value[$queryInfo['index']['column']]][] = $value;
}else{
$data[$value[$queryInfo['index']['column']]] = $value;
}
}
return $data;
}
return $result;
}
/**
* select function alias
*/
public function get($queryInfo){ return $this->select($queryInfo);}
/**
* Get one row from table
*
* @param array $queryInfo
*
* @return array
*/
public function load($queryInfo){
$sql = $this->buildQuery('select', $queryInfo);
$results = $this->query($sql);
return $results->fetch();
}
/**
* Insert data to table
*
* @param array $queryInfo (
* 'table'=>'Table Name',
* 'values'=>['name' => 'arash', 'company'=>'leomoon']
* );
*
* @return int 1 or null
*/
public function insert($queryInfo){
$sql = $this->buildQuery('insert', $queryInfo);
return $this->exec($sql);
}
/**
* Update rows
*
* @param array $queryInfo (
* 'table'=>'Table Name',
* 'where'=>['IQ' => 0], // - (optional)
* 'values'=>['name' => 'trump', 'role'=>'president']
* );
*
* @return int 1 or null
*/
public function update($queryInfo){
$sql = $this->buildQuery('update', $queryInfo);
return $this->exec($sql);
}
/**
* Delete rows
*
* @param array $queryInfo (
* 'table'=>'Table Name',
* 'where'=>['status' => 0], // - (optional)
* 'limit'=> 1 // - (optional)
* );
*
* @return int 1 or null
*/
public function delete($queryInfo){
$sql = $this->buildQuery('delete', $queryInfo);
return $this->exec($sql);
}
/**
* Simple search
* @param array $queryInfo (
* 'table'=>'Table Name',
* 'fields'=>'id, title', // - (optional)
* 'searchs'=>['title', 'body'], // or search in all fields - (optional)
* 'word'=>'%YourSearchWord%', // %word% or %word or word%
* 'where'=>['category' => 'news'], // - (optional)
* 'limit'=> 10 // - (optional)
* 'order'=>'publish_date DESC'
* );
*
* @return array
*/
public function search($queryInfo){
$sql = $this->buildQuery('search', $queryInfo);
$query = $this->query($sql);
return $query->fetchAll();
}
/**
* PDO prepare and execute
*
*/
public function query($sql){
$stmt = $this->mypdo->prepare($sql);
$stmt->execute();
if(!$stmt){
$error = $this->mypdo->errorInfo();
if(!is_null($error[2])){
$this->errorMessage = $error[2];
}
}
return $stmt;
}
/**
* PDO exec - run your custom query
*
* @param string $sql
*/
public function exec($sql){
$this->mypdo->exec($sql);
$error = $this->mypdo->errorInfo();
if(!is_null($error[2])){
$this->errorMessage = $error[2];
}
}
/**
* Get total rows from table
*
* @param array $queryInfo
*
* @return int
*/
public function count($queryInfo){
$sql = $this->buildQuery('count', $queryInfo);
return $this->mypdo->query($sql)->fetchColumn();
}
/**
* count function alias
*/
public function total($queryInfo){
return $this->count($queryInfo);
}
/**
* Get the last inserted id
*
*/
public function insertId(){
return $this->mypdo->lastInsertId();
}
/**
* Show tables and columns
*
* @param array $queryInfo
*/
public function schema($queryInfo=null){
if(isset($queryInfo['table'])){
$sql = "DESCRIBE ".$queryInfo['table'];
}else{
$sql = "SHOW TABLES";
}
$data = $this->query($sql);
return $data->fetchAll();
}
/**
* Build sql query for select, update, insert, delete, search
*
* @param string $action
* @param array $queryInfo
*
* @return string
*/
private function buildQuery($action, $queryInfo){
if(in_array($action, ['select', 'search'])){
$query = "SELECT ";
if(isset($queryInfo['fields'])){
$query .= $queryInfo['fields'];
}else{
$query .= "*";
}
$query .= " FROM ".$queryInfo['table'];
}
if($action == 'update'){
$query = "UPDATE ".$queryInfo['table']." SET ".$this->buildUpdateQuery($queryInfo['values']);
}
if($action == 'delete'){
$query = "DELETE FROM ".$queryInfo['table'];
}
if($action == 'insert'){
$query = "INSERT INTO ".$queryInfo['table'];
$values = [];
foreach($queryInfo['values'] as $key=>$value){
if($value != NULL){
$values[$key] = $value;
}
}
$query .= " (`".implode('`,`', array_keys($values))."`) VALUES ('".implode("','", array_values($values))."')";
}
if($action == 'count'){
$query = "SELECT COUNT(1) FROM ".$queryInfo['table'];
}
if(isset($queryInfo['where'])){
if(is_array($queryInfo['where'])){
$query .= " WHERE ". $this->buildWhereQuery($queryInfo['where']);
}else{
$query .= " WHERE ".$queryInfo['where'];
}
}
if(isset($queryInfo['word'])){
$query .= $this->buildSearchQuery($queryInfo);
}
if(isset($queryInfo['order'])){
$query .= " ORDER BY ".$queryInfo['order'];
}
if(isset($queryInfo['limit'])){
$query .= " LIMIT ".$queryInfo['limit'];
}
if(isset($queryInfo['sql'])){
$query = $queryInfo['sql'];
}
$this->sqlQuery = $query;
return $query;
}
/**
* Build WHERE query (key-value)
* @param array
*
* @return string
*/
private function buildWhereQuery($where){
$query = "";
if($where){
$comma = "";
foreach ($where as $key=>$value) {
$query.="$comma `$key`='$value' ";
$comma=' AND ';
}
}
return $query;
}
/**
* Build Update query (key-value)
* @param array
*
* @return string
*/
private function buildUpdateQuery($values){
$query = "";
if($values){
$comma = "";
foreach ($values as $key=>$value) {
if($value != NULL){
$query.="$comma `$key`='$value' ";
}else{
$query .= "$comma `$key`=NULL ";
}
$comma=', ';
}
}
return $query;
}
/**
* Build search query
* @param array
*
* @return string
*/
private function buildSearchQuery($queryInfo){
if(isset($queryInfo['where'])){
$sql = " AND ";
}else{
$sql = " WHERE ";
}
if(!isset($queryInfo['searchs'])){
$tableFields = $this->schema(['table'=>$queryInfo['table']]);
foreach($tableFields as $field){
$queryInfo['searchs'][] = $field['Field'];
}
}
$comma = "";
$keyword = $queryInfo['word'];
foreach($queryInfo['searchs'] as $column){
$sql .= "$comma `$column` LIKE '$keyword'";
$comma=" OR ";
}
return $sql;
}
/**
* Show errors
*/
public function error(){
echo $this->errorMessage."\r\n";
}
}
?>