-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtable.php
464 lines (410 loc) · 12.3 KB
/
table.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
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
<?php
class table
{
/**
* A pointer to the controller who made me. (it has a core)
* @var controller
*/
public $controller = null;
public $table = ''; // The table name of this table
public $key = ''; // The primary key of this table
private static $instance = null; // an instance of this class
private $cacheNextQuery = false; // use cacheNextQuery() before doing query and it will be cached or returned from cache
private $debugNextQuery = false; // use debugNextQuery() before doing a query and it will be displayed instead of performed
private $cache = array();
/**
* The last executed query;
*/
public $lastQuery;
/**
* The result of the last executed query;
*/
public $lastResult;
public function table($controller)
{
$this->controller = $controller;
$this->init();
}
public static function getInstance()
{
if(self::$instance === null) self::$instance = new table();
return self::$instance;
}
protected function init()
{
// Override me with your own constructor.
}
private function connectDB()
{
if(is_null($this->controller->core->dbase))
{
if(isset_true($this->controller->core->config['dbase_host']))
{
$this->controller->core->dbase = mysqli_connect
(
$this->controller->core->config['dbase_host'],
$this->controller->core->config['dbase_user'],
$this->controller->core->config['dbase_pass']
);
if(!mysqli_select_db($this->controller->core->dbase, $this->controller->core->config['dbase_dbase']))
{
$this->controller->core->error('Cannot connect to database.');
}
}
else
{
$this->controller->core->error('Database not configured.');
}
}
}
/**
* $query will be queried to the database, this function should be used for SELECTs
* $depth determines wether to return a 2-dimensional array, an array which is a row, col,
* or just the single value
* $depth can be "ALL", "COL", "ROW", or "CELL".
* returns empty array if empty
*/
public function query($query, $depth='ALL', $checkSelect=true)
{
if($this->cacheNextQuery && isset($this->cache[md5($query)])) return $this->cache[md5($query)];
$this->connectDB();
if($checkSelect && substr(trim($query), 0, 6) != 'SELECT') $this->controller->core->error('query() wants a SELECT query. not<br />'.$query);
$this->lastQuery = $query;
$this->debug($query);
$result = mysqli_query($this->controller->core->dbase, $query);
if(!$result) $this->controller->core->error("Query Failed.<hr /><pre>$query");
$count = mysqli_num_rows($result);
$data = array();
for ($i=0; $i < $count; $i++)
{
if($depth=='COL' || $depth=='CELL')
{
$row = mysqli_fetch_array($result, MYSQL_NUM);
$data[] = $row[0];
}
else // ALL or ROW
{
$data[] = mysqli_fetch_array($result, MYSQL_ASSOC);
}
}
// If we're just returning 1 row, just return that one row
if($depth=='ROW' && count($data)) $data = $data[0];
// If we're just returning one cell, just get that piece of data.
if($depth=='CELL')
{
if(count($data))
{
$data = $data[0];
}
else
{
$data = '';
}
}
$this->controller->core->stats['queryCount']++;
if($this->cacheNextQuery) return $this->cache[md5($query)] = $data;
return $data;
}
/**
* Use this to run UPDATE queries on the database
* It will return the number of affected rows
*/
public function update($query)
{
$this->connectDB();
$this->lastQuery = $query;
$this->debug($query);
$result = mysqli_query($this->controller->core->dbase, $query);
$this->lastResult = $result;
if(!$result) $this->controller->core->error("Query Failed.<hr /><pre>$query");
$this->controller->core->stats['updateCount']++;
return mysqli_affected_rows($this->controller->core->dbase);
}
/**
* Cleans a string. should be used before entering data into a query.
*/
public function clean($string){
return mysqli_real_escape_string($this->controller->core->dbase, $string);
}
/**
* Use this to run INSERT queries on the database
* It will return the ID of the last inserted row
*/
public function insert($query)
{
$this->connectDB();
$this->debug($query);
$result = mysqli_query($this->controller->core->dbase, $query);
if(!$result) $this->controller->core->error("Query Failed.<hr /><pre>$query");
$this->controller->core->stats['updateCount']++;
return mysqli_insert_id($this->controller->core->dbase);
}
/**
* Param 1 can be 1 col eg: "name", or several eg: "name, email"
* Param 2 depends on the datatype you give it:
* Default: "WHERE 1" n rows
* Integer: "WHERE primary_key = <yourInt>" 1 row
* String: "WHERE <yourString>" n rows
*/
public function get($cols='*', $where=null, $sort=1, $join='', $limit='', $offset='')
{
if($this->table == '') $this->controller->core->error('Tables need the $table set.');
if($cols=='*' && $join) $this->controller->core->error('You shouldnt select for * when using a join. Its likely some columns will overlap.');
if($limit) $limit=$this->clean($limit);
if($offset) $offset=$this->clean($offset);
if($limit && $offset) $limit = "LIMIT $offset, $limit";
if($limit && !$offset) $limit = "LIMIT $limit";
$depth = 'ALL';
if(!strstr($cols, '*') && !strpos($cols,',')) $depth = 'COL';
if($where == null)
{
$where = 1;
}
elseif(is_numeric($where))
{
if($this->key == '') $this->controller->core->error($this->table.' table need the $key set to use get(string, int).');
$where = "$this->key = $where";
if($depth=='COL')
{
$depth = 'CELL';
}
else
{
$depth = 'ROW';
}
}
$query = "SELECT $cols FROM `$this->table` $join WHERE $where ORDER BY $sort $limit;";
return $this->query($query, $depth);
}
public function getCount($where=1)
{
if($this->table == '') $this->controller->core->error('Tables need the $table set.');
$return = $this->query("SELECT COUNT(1) FROM `$this->table` WHERE $where", 'CELL');
return $return;
}
/**
* Returns the number of affected rows
* Param 1 must be the col name
* Param 2 must be the val to set it to
* Param 3 depends on the datatype you give it:
* Default: "WHERE 1"
* Integer: "WHERE primary_key = <yourInt>"
* String: "WHERE <yourString>"
*/
public function set($what=false, $to=false, $where=null)
{
$return = false;
if($what && $to)
{
if($where == null)
{
$where = 1;
}
elseif(is_numeric($where))
{
if($this->key == '') $this->controller->core->error($this->table.' table need the $key set to use set(string, string, int).');
$where = "$this->key = $where";
}
$return = $this->update("UPDATE $this->table SET $what = $to WHERE $where;");
}
return $return;
}
/**
* Get a list of tables in this database.
*/
public function getTables()
{
$dbase = $this->controller->core->config['dbase_dbase'];
$sql = "show table status from `$dbase` where engine is not NULL";
return $this->query($sql,'COL',false);
}
/**
* Assuming the mysql bin directory is configured in the config.ini,
* This will try its luck at doing a mysql dump.
*/
public function sqlDump()
{
if(!isset_true($this->controller->core->config['mysql_dir']))
{
$error = 'mysql_dir needs to be defined in your config.ini.';
$error.= '<br />eg.: mysql_dir = "C:\\programming\\php\\wamp\\bin\\mysql\\mysql5.0.45\\bin\\"';
$this->controller->core->error($error);
}
elseif(!isset_true($this->controller->core->config['dbase_host']))
{
$this->controller->core->error('dbase details need to be defined in your config.ini.');
}
else
{
$dbase = $this->controller->core->config['dbase_dbase'];
$host = '-h'.$this->controller->core->config['dbase_host'];
$user = '-u'.$this->controller->core->config['dbase_user'];
$mysqldump = $this->controller->core->config['mysql_dir'].'mysqldump.exe';
$pass = ($this->controller->core->config['dbase_pass'] ? '-p'.$this->controller->core->config['dbase_pass'] : '');
$options = '--add-drop-database';
if($user == 'root') $options .= ' --lock-all-tables';
$string = "$mysqldump $host $user $pass $options $dbase";
print $string.'<br />';
print 'DUMPING...';
ob_flush();
flush();
$data = `$string`; // Like system(), but returns string and doesn't print.
print ($data ? 'DUMP OK<br />' : 'DUMP ERROR<br />');
print 'WRITING...';
ob_flush();
flush();
$h = fopen('../etc/dbase.sql','w');
$success = fwrite($h, $data);
print ($success ? 'WRITE OK' : 'WRITE ERROR');
if($success) print "<hr /><pre>$data</pre>";
}
exit; // We don't want them sqlDumping again accidentally.
}
// Row functions
/**
* Returns a new empty row belonging to this table.
* @return row
*/
public function createRow($userID = false)
{
$file = "../app/_tables/".$this->table.'Row.php';
if(file_exists($file)) {
require_once($file);
$class = $this->table.'Row';
$row = new $class($this);
}
else
{
$row = new row($this);
}
if($userID){
$row->create_user_id = $userID;
$row->create_date = time();
$row->edit_user_id = $userID;
$row->edit_date = time();
}
return $row;
}
/**
* Gets a row of this table, returns the row object.
* @return row
*/
public function getRow($id=0)
{
$row = $this->createRow();
$row->_key = $id;
$data = $this->get('*',$id);
if(sizeof($data)==1) $data = $data[0];
foreach($data as $key => $val) $row->$key = $val;
return $row;
}
/**
* Gets several rows of this table, returns the row objects in an array.
* @return unknown array(row)
*/
public function getRows($cols='*', $where=null, $sort=1, $join='', $limit='', $offset='')
{
$data=$this->get($cols, $where, $sort, $join, $limit, $offset);
$rows = array();
foreach($data as $rowArray)
{
$rowObject = $this->createRow();
foreach($rowArray as $key => $val) $rowObject->$key = $val;
$rows[] = $rowObject;
}
return $rows;
}
/**
* Used by the row class. do not use.
*/
public function rowInsert($data = array())
{
$sql = "INSERT INTO `$this->table` (`";
$sql .= implode('`, `',array_keys($data));
$sql .= '`) VALUES ("';
$sql .= implode('", "',$data);
$sql .= '");';
return $this->insert($sql);
}
/**
* Used by the row class. do not use.
*/
public function rowUpdate($data=array(), $keyVal=0)
{
$sql = "UPDATE `$this->table` SET ";
$elements = array();
foreach ($data as $key => $val) $elements[] = "`$key`='$val'";
$sql .= implode(', ', $elements);
$sql .= " WHERE `$this->key` = '$keyVal'";
return $this->update($sql);
}
private function debug($query) {
if(!$this->controller->core->config['debug']) return;
if($this->debugNextQuery) {
debug($query);
exit;
}
$trace=debug_backtrace();
$i=0;
$file = $trace[$i];
while(strstr($file['file'], 'redphp')) {
$file = $trace[++$i];
}
$string = $file['file'].' ('.$file['line']."):\n";
$log = $string . $query;
$this->controller->core->queries[] = $log;
if(!isset_true($_GET['sql-log'])) {
$date = date('Y-m-d H:i:s');
file_put_contents(_LOG_DIR_.'/site-sql.log', "\n\n$date\n$log", FILE_APPEND);
}
}
public function beginTransaction(){
$this->connectDB();
mysqli_autocommit($this->controller->core->dbase, false);
}
public function rollBack(){
$this->connectDB();
mysqli_rollback($this->controller->core->dbase);
mysqli_autocommit($this->controller->core->dbase, true);
}
public function endTransaction(){
$this->connectDB();
mysqli_commit($this->controller->core->dbase);
mysqli_autocommit($this->controller->core->dbase, true);
}
public function cacheNextQuery(){
$this->cacheNextQuery = true;
}
/**
* Takes a column name like "email_address" and fancifies it to "Email Address"
*/
public function fancify($str){
$str = str_replace('_', ' ', $str);
$str = str_replace('-', ' ', $str);
$str = ucwords($str);
return $str;
}
/**
* Takes a fancy column name like "Email Address" and unfancifies it to "email_address"
* Also fancifies column_id to Column ID
*/
public function unfancify($str){
// $str = str_replace(' ', '_', $str);
$str = explode('_', $str);
$a = array();
foreach($str as $word)
{
if(strtolower($word)=='id') $word="ID";
$a[] = $word;
}
$str = implode(' ', $word);
$str = strtolower($str);
return $str;
}
/**
* Used for debug purposes. Insted of actually performing the query, just generates it and spits it out.
*/
public function debugNextQuery(){
$this->debugNextQuery = true;
}
}