/
bxaf_mysqli.php
660 lines (660 loc) · 21.2 KB
/
bxaf_mysqli.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
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
<?php
class bxaf_mysqli
{
private $conn;
private $stats;
private $show_error;
private $error_output;
private $fetch_mode;
private $defaults = array('host' => 'localhost', 'user' => 'root', 'pass' => '', 'db' => 'test', 'port' => 3306, 'socket' => NULL, 'pconnect' => TRUE, 'fetch_mode' => MYSQLI_ASSOC, 'flags' => NULL, 'charset' => 'utf8', 'show_error' => 0, 'error_output' => 'bxaf_mysqli.errors.txt');
function __construct($opt = array())
{
$opt = array_merge($this->defaults, $opt);
$this->show_error = $opt['show_error'];
$this->error_output = $opt['error_output'];
if ($opt['fetch_mode'] == MYSQLI_NUM)
$this->fetch_mode = MYSQLI_NUM;
else
$this->fetch_mode = MYSQLI_ASSOC;
if (isset($opt['mysqli'])) {
if ($opt['mysqli'] instanceof mysqli) {
$this->conn = $opt['mysqli'];
return;
} else {
$this->error("mysqli option must be valid instance of mysqli class");
}
}
if (($opt['host'] == 'localhost') || ($opt['host'] == '127.0.0.1')) {
if ($opt['pconnect'])
$opt['host'] = "p:" . $opt['host'];
$this->conn = mysqli_connect($opt['host'], $opt['user'], $opt['pass'], $opt['db'], $opt['port'], $opt['socket']);
if (mysqli_connect_errno()) {
die("Connect failed: %s\n" . mysqli_connect_error());
}
if (!$this->conn) {
$this->error(mysqli_connect_errno() . " " . mysqli_connect_error());
}
} else {
if ($opt['pconnect'])
$opt['host'] = "p:" . $opt['host'];
$this->conn = mysqli_init();
if ($this->conn) {
if (!mysqli_real_connect($this->conn, $opt['host'], $opt['user'], $opt['pass'], $opt['db'], $opt['port'], $opt['socket'], $opt['flags'])) {
$this->error(mysqli_connect_errno() . " " . mysqli_connect_error());
}
} else {
die('mysqli_init failed.');
}
}
mysqli_set_charset($this->conn, $opt['charset']) or $this->error(mysqli_error($this->conn));
unset($opt);
}
public function query()
{
return $this->raw_query($this->prepare_query(func_get_args()));
}
public function Execute()
{
return $this->raw_query($this->prepare_query(func_get_args()));
}
public function fetch($result)
{
$mode = $this->fetch_mode == MYSQLI_NUM ? MYSQLI_NUM : MYSQLI_ASSOC;
return mysqli_fetch_array($result, $mode);
}
public function affected_rows()
{
return mysqli_affected_rows($this->conn);
}
public function insert_id()
{
return mysqli_insert_id($this->conn);
}
public function num_rows($result)
{
return mysqli_num_rows($result);
}
public function field_count($result)
{
return mysqli_num_fields($result);
}
public function num_fields($result)
{
return mysqli_num_fields($result);
}
public function free($result)
{
mysqli_free_result($result);
}
public function get_one()
{
$query = $this->prepare_query(func_get_args());
if ($res = $this->raw_query($query)) {
$row = $this->fetch($res);
if (is_array($row)) {
return reset($row);
}
$this->free($res);
}
return FALSE;
}
public function GetOne()
{
return $this->get_one($this->prepare_query(func_get_args()));
}
public function get_row()
{
$query = $this->prepare_query(func_get_args());
if ($res = $this->raw_query($query)) {
$ret = $this->fetch($res);
$this->free($res);
return $ret;
}
return FALSE;
}
public function GetRow()
{
return $this->get_row($this->prepare_query(func_get_args()));
}
public function get_col()
{
$ret = array();
$query = $this->prepare_query(func_get_args());
if ($res = $this->raw_query($query)) {
while ($row = $this->fetch($res)) {
$ret[] = reset($row);
}
$this->free($res);
}
return $ret;
}
public function GetCol()
{
return $this->get_col($this->prepare_query(func_get_args()));
}
public function get_all()
{
$ret = array();
$query = $this->prepare_query(func_get_args());
if ($res = $this->raw_query($query)) {
$mode = $this->fetch_mode == MYSQLI_NUM ? MYSQLI_NUM : MYSQLI_ASSOC;
$ret = mysqli_fetch_all($res, $mode);
$this->free($res);
}
return $ret;
}
public function GetAll()
{
return $this->get_all($this->prepare_query(func_get_args()));
}
public function GetArray()
{
return $this->get_all($this->prepare_query(func_get_args()));
}
public function get_assoc()
{
$args = func_get_args();
$index = array_shift($args);
$query = $this->prepare_query($args);
$ret = array();
if ($res = $this->raw_query($query)) {
$num_fields = $this->num_fields($res);
if ($num_fields <= 1) {
} else if ($num_fields == 2) {
while ($row = $this->fetch($res)) {
if (array_key_exists($index, $row)) {
$key = $row[$index];
unset($row[$index]);
$value = array_pop($row);
$ret[$key] = $value;
}
}
} else {
while ($row = $this->fetch($res)) {
if (array_key_exists($index, $row)) {
$key = $row[$index];
unset($row[$index]);
$ret[$key] = $row;
}
}
}
$this->free($res);
}
return $ret;
}
public function GetAssoc()
{
$query = $this->prepare_query(func_get_args());
$ret = array();
if ($res = $this->raw_query($query)) {
$num_fields = $this->num_fields($res);
if ($num_fields <= 1) {
} else if ($num_fields == 2) {
while ($row = $this->fetch($res)) {
$second = array_pop($row);
$first = array_pop($row);
$ret[$first] = $second;
}
} else {
while ($row = $this->fetch($res)) {
$first = array_shift($row);
$ret[$first] = $row;
}
}
$this->free($res);
}
return $ret;
}
public function get_assoc_col()
{
$args = func_get_args();
$index = array_shift($args);
$query = $this->prepare_query($args);
$ret = array();
if ($res = $this->raw_query($query)) {
while ($row = $this->fetch($res)) {
$key = $row[$index];
unset($row[$index]);
$ret[$key] = reset($row);
}
$this->free($res);
}
return $ret;
}
public function GetAssocCol()
{
return $this->get_assoc_col($this->prepare_query(func_get_args()));
}
public function parse()
{
return $this->prepare_query(func_get_args());
}
public function white_list($input, $allowed, $default = FALSE)
{
$found = array_search($input, $allowed);
return ($found === FALSE) ? $default : $allowed[$found];
}
public function filter_array($input, $allowed)
{
foreach (array_keys($input) as $key) {
if (!in_array($key, $allowed)) {
unset($input[$key]);
}
}
return $input;
}
public function last_query()
{
$last = end($this->stats);
return $last['query'];
}
public function get_stats()
{
return $this->stats;
}
public function get_id()
{
$args = func_get_args();
$table = array_shift($args);
$condition = $this->prepare_query($args);
$sql = "SELECT `ID` FROM ?n ";
if (trim($condition) != '')
$sql .= " WHERE ?p";
return $this->get_one($sql, $table, $condition);
}
public function get_ids()
{
$args = func_get_args();
$table = array_shift($args);
$condition = $this->prepare_query($args);
$sql = "SELECT `ID` FROM ?n ";
if (trim($condition) != '')
$sql .= " WHERE ?p";
return $this->get_col($sql, $table, $condition);
}
public function delete()
{
$args = func_get_args();
$table = array_shift($args);
$condition = $this->prepare_query($args);
$sql = "DELETE FROM ?n WHERE ?p";
$query = $this->parse($sql, $table, $condition);
$affected_rows = 0;
if ($res = $this->raw_query($query)) {
$affected_rows = $this->affected_rows();
$this->free($res);
}
return $this->affected_rows();
}
public function update()
{
$args = func_get_args();
$table = array_shift($args);
$field_values = array_shift($args);
if (!is_array($field_values) || count($field_values) <= 0)
return false;
$condition = $this->prepare_query($args);
$sql = "UPDATE ?n SET ?u WHERE ?p";
$query = $this->parse($sql, $table, $field_values, $condition);
$affected_rows = 0;
if ($res = $this->raw_query($query)) {
$affected_rows = $this->affected_rows();
$this->free($res);
}
return $this->affected_rows();
}
public function update_batch()
{
$args = func_get_args();
$table = array_shift($args);
$field = array_shift($args);
$field_values = array_shift($args);
if (!is_array($field_values) || count($field_values) <= 0)
return false;
$condition = $this->prepare_query($args);
$affected_rows = 0;
foreach ($field_values as $field_value) {
if (!is_array($field_value) || count($field_value) <= 0)
continue;
if (!array_key_exists($field, $field_value))
continue;
$cond = "?n = ?s";
if (trim($condition) != '')
$cond .= " AND ?p";
$cond = $this->parse($cond, $field, $field_value[$field], $condition);
unset($field_value[$field]);
$sql = "UPDATE ?n SET ?u";
if (trim($cond) != '')
$sql .= " WHERE ?p";
$query = $this->parse($sql, $table, $field_value, $cond);
if ($res = $this->raw_query($query)) {
$affected_rows += $this->affected_rows();
$this->free($res);
}
}
return $affected_rows;
}
public function batch_update()
{
return $this->update_batch($this->prepare_query(func_get_args()));
}
public function updateBatch()
{
return $this->update_batch($this->prepare_query(func_get_args()));
}
public function batchUpdate()
{
return $this->update_batch($this->prepare_query(func_get_args()));
}
public function insert()
{
$args = func_get_args();
$table = array_shift($args);
$field_values = array_shift($args);
if (!is_array($field_values) || count($field_values) <= 0)
return false;
$condition = $this->prepare_query($args);
$sql = "INSERT INTO ?n SET ?u";
if (trim($condition) != '')
$sql .= " WHERE ?p";
$query = $this->parse($sql, $table, $field_values, $condition);
$insert_id = 0;
if ($res = $this->raw_query($query)) {
$insert_id = $this->insert_id();
$this->free($res);
}
return $insert_id;
}
public function replace()
{
$args = func_get_args();
$table = array_shift($args);
$field_values = array_shift($args);
if (!is_array($field_values) || count($field_values) <= 0)
return false;
$condition = $this->prepare_query($args);
$sql = "REPLACE INTO ?n SET ?u";
if (trim($condition) != '')
$sql .= " WHERE ?p";
$query = $this->parse($sql, $table, $field_values, $condition);
$insert_id = 0;
if ($res = $this->raw_query($query)) {
$insert_id = $this->insert_id();
$this->free($res);
}
return $insert_id;
}
public function insert_batch()
{
$args = func_get_args();
$table = array_shift($args);
$field_values = array_shift($args);
if (!is_array($field_values) || count($field_values) <= 0)
return false;
$condition = $this->prepare_query($args);
$insert_ids = array();
foreach ($field_values as $field_value) {
if (!is_array($field_value) || count($field_value) <= 0)
continue;
$sql = "INSERT INTO ?n SET ?u";
if (trim($condition) != '')
$sql .= " WHERE ?p";
$query = $this->parse($sql, $table, $field_value, $condition);
if ($res = $this->raw_query($query)) {
$id = $this->insert_id();
if ($id > 0)
$insert_ids[] = $id;
$this->free($res);
}
}
return $insert_ids;
}
public function insertBatch()
{
return $this->insert_batch($this->prepare_query(func_get_args()));
}
public function batch_insert()
{
return $this->insert_batch($this->prepare_query(func_get_args()));
}
public function batchInsert()
{
return $this->insert_batch($this->prepare_query(func_get_args()));
}
public function replace_batch()
{
$args = func_get_args();
$table = array_shift($args);
$field_values = array_shift($args);
if (!is_array($field_values) || count($field_values) <= 0)
return false;
$condition = $this->prepare_query($args);
$insert_ids = array();
foreach ($field_values as $field_value) {
if (!is_array($field_value) || count($field_value) <= 0)
continue;
$sql = "REPLACE INTO ?n SET ?u";
if (trim($condition) != '')
$sql .= " WHERE ?p";
$query = $this->parse($sql, $table, $field_value, $condition);
if ($res = $this->raw_query($query)) {
$id = $this->insert_id();
if ($id > 0)
$insert_ids[] = $id;
$this->free($res);
}
}
return $insert_ids;
}
public function batchReplace()
{
return $this->replace_batch($this->prepare_query(func_get_args()));
}
public function replaceBatch()
{
return $this->replace_batch($this->prepare_query(func_get_args()));
}
public function batch_replace()
{
return $this->replace_batch($this->prepare_query(func_get_args()));
}
public function get_column_names($table)
{
$sql = "DESCRIBE ?n";
$query = $this->parse($sql, $table);
return $this->get_col($query);
}
public function MetaColumnNames($table)
{
$colnames = $this->get_column_names($table);
$MetaColumnNames = array();
foreach ($colnames as $k => $v)
$MetaColumnNames[strtoupper($v)] = $v;
return $MetaColumnNames;
}
public function set_fetch_mode($mode)
{
if ($mode == MYSQLI_NUM)
$this->fetch_mode = MYSQLI_NUM;
else
$this->fetch_mode = MYSQLI_ASSOC;
}
public function SetFetchMode($mode)
{
if ($mode == 1)
$this->fetch_mode = MYSQLI_NUM;
else
$this->fetch_mode = MYSQLI_ASSOC;
}
public function get_conn()
{
return $this->conn;
}
public function ping()
{
return mysqli_ping($this->conn);
}
public function IsConnected()
{
return mysqli_ping($this->conn);
}
private function raw_query($query)
{
$start = microtime(TRUE);
$res = mysqli_query($this->conn, $query);
$timer = microtime(TRUE) - $start;
$this->stats[] = array(
'query' => $query,
'start' => $start,
'timer' => $timer
);
if (!$res) {
$error = mysqli_error($this->conn);
end($this->stats);
$key = key($this->stats);
$this->stats[$key]['error'] = $error;
$this->cutStats();
$this->error("$error. Full query: [$query]");
}
$this->cutStats();
return $res;
}
private function prepare_query($args)
{
$query = '';
$raw = array_shift($args);
$array = preg_split('~(\?[nsiuap])~u', $raw, null, PREG_SPLIT_DELIM_CAPTURE);
$anum = count($args);
$pnum = floor(count($array) / 2);
if ($pnum != $anum) {
$this->error("Number of args ($anum) doesn't match number of placeholders ($pnum) in [$raw]");
}
foreach ($array as $i => $part) {
if (($i % 2) == 0) {
$query .= $part;
continue;
}
$value = array_shift($args);
switch ($part) {
case '?n':
$part = $this->escapeIdent($value);
break;
case '?s':
$part = $this->escapeString($value);
break;
case '?i':
$part = $this->escapeInt($value);
break;
case '?a':
$part = $this->createIN($value);
break;
case '?u':
$part = $this->createSET($value);
break;
case '?p':
$part = $value;
break;
}
$query .= $part;
}
return $query;
}
private function escapeInt($value)
{
if ($value === NULL) {
return 'NULL';
}
if (!is_numeric($value)) {
$this->error("Integer (?i) placeholder expects numeric value, " . gettype($value) . " given");
return FALSE;
}
if (is_float($value)) {
$value = number_format($value, 0, '.', '');
}
return $value;
}
private function escapeString($value)
{
if ($value === NULL) {
return 'NULL';
}
return "'" . mysqli_real_escape_string($this->conn, $value) . "'";
}
public function qstr()
{
return $this->escapeString($this->prepare_query(func_get_args()));
}
private function escapeIdent($value)
{
if ($value) {
return "`" . str_replace("`", "``", $value) . "`";
} else {
$this->error("Empty value for identifier (?n) placeholder");
}
}
private function createIN($data)
{
if (!is_array($data)) {
$this->error("Value for IN (?a) placeholder should be array");
return;
}
if (!$data) {
return 'NULL';
}
$query = $comma = '';
foreach ($data as $value) {
$query .= $comma . $this->escapeString($value);
$comma = ",";
}
return $query;
}
private function createSET($data)
{
if (!is_array($data)) {
$this->error("SET (?u) placeholder expects array, " . gettype($data) . " given");
return;
}
if (!$data) {
$this->error("Empty array for SET (?u) placeholder");
return;
}
$query = $comma = '';
foreach ($data as $key => $value) {
$query .= $comma . $this->escapeIdent($key) . '=' . $this->escapeString($value);
$comma = ",";
}
return $query;
}
private function error($err)
{
$err = date('Y-m-d H:i:s') . ' (' . __CLASS__ . "): " . $err;
if ($this->show_error == '1') {
$err .= ". Error initiated in " . $this->caller() . ". \n";
$fp = fopen(dirname(__FILE__) . '/' . $this->error_output, 'a+');
fwrite($fp, $err);
fclose($fp);
}
}
private function caller()
{
$trace = debug_backtrace();
$caller = '';
foreach ($trace as $t) {
if (isset($t['class']) && $t['class'] == __CLASS__) {
$caller = $t['file'] . " on line " . $t['line'];
} else {
break;
}
}
return $caller;
}
private function cutStats()
{
if (count($this->stats) > 100) {
reset($this->stats);
$first = key($this->stats);
unset($this->stats[$first]);
}
}
}
?>