分享自己封装的mysql类 基于pdo

分享自己封装的mysql类 基于pdo

由于经常开发小型系统用不到框架,用原生写又太麻烦干脆封装一个MySQL操作类
用了连贯操作 用法和tp相似 上手快 Db.zip

用法

 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
    $res = Db::table('tbl_user')->where('id', 1)->find();   // 获取单个数据
        $res = Db::table('tbl_user')->order('id', 'desc')->select();     // 获取结果集 排序
        $res = Db::instance()->getLastSql();       // 获取上次执行的sql
        $res = Db::table("tbl_user")->where('id', 2)->update(['name' => '云青']);      // 更新数据
        $res = Db::table("tbl_user")->insert(['account' => 'acc', 'name' => 123]);       // 插入单个数据 并返回插入id
        $res = Db::table("tbl_user")
            ->insertAll(
                [
                    ['account' => 'test1', 'name' => 'test1'], 
                    ['account' => 'test2', 'name' => 'test2']
                ]
            );       // 批量插入数据
        $res = Db::table('tbl_user')->where('id', 5)->delete();       // 删除数据
        $res = Db::table('tbl_user')->tbFields();       // 获取数据表字段
        $res = Db::table('tbl_user')->count('id');      // 统计数据条数
        $res = Db::table('tbl_user')->field('id')->sum();      // 统计id和
        $res = Db::table('tbl_user')->doSql("select * from tbl_user");      // 自定义sql
        $res = Db::instance()->startTrans();        // 开启事务
        $res = Db::table("tbl_user")
            ->insertAll(
                [
                    ['account' => 'test1', 'name' => 'test1'], 
                    ['account' => 'test2', 'test2' => 'test2']
                ]
            );       // 批量插入数据
        $res = Db::instance()->commit();          // 提交
        $res = Db::instance()->rollback();          // 回滚
        $res = Db::table('tbl_user')
            ->field('id')
            ->whereIn('account', 'test1,test2')
            ->where('id', '!=', 2)
            ->select();   // whereIn
        $res = Db::table('tbl_user')    // whereIn
            ->field('id')
            ->whereIn('account', 'test1,test2')
            ->whereIn('name', ['test1', 'test2'], 'or')
            ->where('pmid', '=', 0)
            ->select();

封装类

  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
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
<?php
/**
 * @author anderyly
 * @email admin@aaayun.cc
 * @link http://vclove.cn/
 * @copyright Copyright (c) 2018
 */

namespace ay\lib;

class Db
{

    private static $db;
    private $dbType = 'mysql';
    private $pConnect = true;
    private static $table;
    private $host;
    private $port;
    private $dbName;
    private $user;
    private $pass;
    private $group = '';
    private static $sql = false; //最后一条sql语句
    private $where = '';
    private $order = '';
    private $limit = '';
    private $field = '*';
    private $clear = 0; //状态,0表示查询条件干净,1表示查询条件污染
    private static $trans = 0; //事务指令数

    /**
     * 初始化
     * Dc constructor.
     * @param null $conf 数据库配置
     */
    public function __construct($conf = null)
    {

        class_exists('PDO') or halt("PDO模块不存在");
        if (is_null($conf)) {
            $conf = C();
        }

        $this->dbType = $conf['DB_TYPE'];
        $this->host = $conf['DB_HOST'];
        $this->port = $conf['DB_PORT'];
        $this->user = $conf['DB_USER'];
        $this->pass = $conf['DB_PASS'];
        $this->dbName = $conf['DB_NAME'];

        //连接数据库
        if (is_null(self::$db)) {
            $this->connect();
        }

    }

    /**
     * PDO连接数据库
     * @throws \Exception
     */
    private function connect()
    {
        $dsn = $this->dbType . ':host=' . $this->host . ';port=' . $this->port . ';dbname=' . $this->dbName;
        $options = $this->pConnect ? [\PDO::ATTR_PERSISTENT => true] : [];
        try {
            $dbh = new \PDO($dsn, $this->user, $this->pass, $options);
            $dbh->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
            $dbh->setAttribute(\PDO::ATTR_EMULATE_PREPARES, false);
        } catch (\PDOException $e) {
            throw new \Exception('Connection failed: ' . $e->getMessage());
        }
        $dbh->exec('SET NAMES utf8');
        self::$db = $dbh;
    }

    /**
     * @return object
     */
    public static function instance()
    {
        return new self();
    }

    /**
     * 设置数据表名
     * @param $table
     * @return object
     */
    public static function name($table)
    {
        if (empty($table)) {
            halt('不能设置数据表名为空');
        }

        $tableS = C('DB_PRE') . $table;
        self::$table = self::addChar($tableS);
        return new self();
    }

    /**
     * 设置数据表名
     * @param $table
     * @return object
     */
    public static function table($table)
    {
        if (empty($table)) {
            halt('不能设置数据表名为空');
        }

        self::$table = self::addChar($table);
        return new self();
    }

    /**
     * 设置当前数据表别名
     * @param $alias
     * @return object
     */
    public function alias($alias): object
    {
        if (empty($alias) or empty(self::$table)) {
            halt('数据库表名设置别名为空');
        }

        self::$table .= ' AS ' . $alias;
        return $this;
    }

    private static function addChar($value, $num = 0)
    {
        if (strpos($value, "`") === false and $num == 1 and !is_int($value)) {
            $data = "'" . trim($value) . "'";
        } else if (strpos($value, "`") === false and !is_int($value) and $num != 1) {
            $data = "`" . trim($value) . "`";
        } else {
            $data = trim($value);
        }
        return $data;
    }

    /**
     * 执行查询 主要针对 SELECT, SHOW 等指令
     * @param string $sql
     * @return mixed
     */
    public function doQuery($sql = '', $options = true)
    {
        self::$sql = $sql;

        if ($options) {
            $result = self::$db->query(self::$sql)->fetchAll(\PDO::FETCH_ASSOC);
        } else {
            $result = self::$db->query(self::$sql)->fetch(\PDO::FETCH_ASSOC);
        }

        return $result;
    }

    /**
     * 执行语句 针对 INSERT, UPDATE 以及DELETE,exec结果返回受影响的行数
     * @param string $sql
     * @return mixed
     */
    public function doExec($sql = '', $op = '')
    {
        self::$sql = $sql;
        $res = self::$db->exec(self::$sql);
        if ($op == 'insert') {
            $res = $this->getLastInsId();
        }
        return $res;
    }

    /**
     * 执行sql语句,自动判断进行查询或者执行操作
     * @param string $sql SQL指令
     * @return mixed
     */
    public function doSql($sql = '')
    {
        $queryIps = 'INSERT|UPDATE|DELETE|REPLACE|CREATE|DROP|LOAD DATA|SELECT .* INTO|COPY|ALTER|GRANT|REVOKE|LOCK|UNLOCK';
        if (preg_match('/^\s*"?(' . $queryIps . ')\s+/i', $sql)) {
            return $this->doExec($sql);
        } else {
            return $this->doQuery($sql);
        }
    }

    /**
     * 获取上一次查询的sql
     * @return string
     */
    public function getLastSql()
    {
        return self::$sql;
    }

    /**
     * 插入方法
     * @param array $data
     * @return mixed
     * @throws \Exception
     */
    public function insert(array $data)
    {
        $data = $this->dataFormat($data);
        if (!$data) {
            exit('插入数据不能为空');
        }

        $sql = 'INSERT INTO ' . self::$table . '(' . implode(',', array_keys($data)) . ') VALUES(' . implode(',', array_values($data)) . ')';
        return $this->doExec($sql, 'insert');
    }

    /**
     * 批量插入方法
     * @param array $data
     * @return mixed
     * @throws \Exception
     */
    public function insertAll(array $data)
    {

        $value = '(';
        foreach ($data as $k => $v) {
            foreach ($v as $k1 => $v1) {
                $value .= "'" . $v1 . "',";
            }
            $value = rtrim($value, ',');
            $value .= '), (';
        }
        $value = rtrim($value, ', (');

        $sql = 'INSERT INTO ' . self::$table . '(' . implode(',', array_keys($data[0])) . ') VALUES ' . $value;
        return $this->doExec($sql, false);
    }

    /**
     * 获取最后一次插入时的ID
     * @return mixed
     */
    public function getLastInsId()
    {
        $sql = 'SELECT LAST_INSERT_ID()';
        $res = $this->doQuery($sql, false);
        return isset($res['LAST_INSERT_ID()']) ? $res['LAST_INSERT_ID()'] : 'false';
    }

    /**
     * 删除方法
     * @return mixed
     * @throws \Exception
     */
    public function delete()
    {
        //安全考虑,阻止全表删除
        if (!trim($this->where)) {
            exit('删除条件禁止为空');
        }

        $sql = 'DELETE FROM ' . self::$table . ' ' . $this->where;
        $this->clear = 1;
        $this->clear();
        return $this->doExec($sql);
    }

    /**
     * 更新方法
     * @param array $data
     * @return mixed|void
     * @throws \Exception
     */
    public function update(array $data)
    {
        //安全考虑,阻止全表更新
        if (!trim($this->where)) {
            exit('更新条件禁止为空');
        }

        $data = $this->dataFormat($data);
        if (!$data) {
            return;
        }

        $valArr = array();
        foreach ($data as $k => $v) {
            $valArr[] = $k . '=' . $v;
        }
        $valStr = implode(',', $valArr);
        $sql = 'UPDATE ' . trim(self::$table) . ' SET ' . trim($valStr) . ' ' . trim($this->where);
        return $this->doExec($sql);
    }

    /**
     * 更新语句 字段值加 $number
     * @param array|string $field
     * @param null $number
     * @return mixed|void
     * @throws \Exception
     */
    public function setInc($field, $number = null)
    {
        //安全考虑,阻止全表更新
        if (!trim($this->where)) {
            exit('更新条件禁止为空');
        }

        if (is_array($field)) {
            $data = $this->dataFormat($field);
            if (!$data) {
                return;
            }

            $valArr = array();
            foreach ($data as $k => $v) {
                $valArr[] = $k . '=' . $k . '+' . $v;
            }
            $valStr = implode(',', $valArr);
            $sql = 'UPDATE ' . trim(self::$table) . ' SET ' . trim($valStr) . ' ' . trim($this->where);
        } else if (is_string($field) and is_null($number)) {
            $sql = 'UPDATE ' . trim(self::$table) . ' SET ' . self::addChar($field) . '=' . self::addChar($field) . '+1 ' . trim($this->where);
        } else {
            $sql = 'UPDATE ' . trim(self::$table) . ' SET ' . self::addChar($field) . '=' . self::addChar($field) . '+' . self::addChar($number, 1) . ' ' . trim($this->where);
        }
        return $this->doExec($sql);

    }

    /**
     * 更新语句 字段值减 $number
     * @param array|string $field
     * @param null $number
     * @return mixed|void
     * @throws \Exception
     */
    public function setDec($field, $number = null)
    {
        //安全考虑,阻止全表更新
        if (!trim($this->where)) {
            exit('更新条件禁止为空');
        }

        if (is_array($field)) {
            $data = $this->dataFormat($field);
            if (!$data) {
                return;
            }

            $valArr = array();
            foreach ($data as $k => $v) {
                $valArr[] = $k . '=' . $k . '-' . $v;
            }
            $valStr = implode(',', $valArr);
            $sql = 'UPDATE ' . trim(self::$table) . ' SET ' . trim($valStr) . ' ' . trim($this->where);
        } else if (is_string($field) and is_null($number)) {
            $sql = 'UPDATE ' . trim(self::$table) . ' SET ' . self::addChar($field) . '=' . self::addChar($field) . '-1 ' . trim($this->where);
        } else {
            $sql = 'UPDATE ' . trim(self::$table) . ' SET ' . self::addChar($field) . '=' . self::addChar($field) . '-' . self::addChar($number, 1) . ' ' . trim($this->where);
        }
        return $this->doExec($sql);

    }

    /**
     * 查询函数
     * @return array|boolean 结果集
     */
    public function select()
    {
        $sql = 'SELECT ' . trim($this->field) . ' FROM ' . self::$table . ' ' . trim($this->where) . ' ' . trim($this->order) . ' ' . trim($this->limit) . " " . trim($this->group);
        $this->clear = 1;
        $this->clear();
        $res = $this->doQuery(trim($sql));
        return isset($res[0]) ? $res : [];
    }

    /**
     * 查询函数
     * @return array|boolean 结果集
     */
    public function find()
    {
        $sql = "SELECT " . trim($this->field) . " FROM " . self::$table . " " . trim($this->where) . " " . trim($this->order) . " " . trim(" LIMIT 1") . " " . trim($this->group);
        $this->clear = 1;
        $this->clear();
        return $this->doQuery(trim($sql), false);

    }

    /**
     * 设置条件
     * @param string | array $option
     * @param string $where
     * @param string $value
     * @return $this
     */
    public function where($option, $where = null, $value = null)
    {
        if ($this->clear > 0) {
            $this->clear();
        }

        // 判断之前是否使用where语句
        if (strpos($this->where, 'WHERE')) {
            $this->where .= ' AND ';
            $useWhere = 1;
        } else {
            $this->where = ' WHERE ';
        }

        // 判断第一个参数为字符
        if (is_string($option)) {
            // 当三个参数都为字符串
            if (!is_null($value)):
                $this->where .= $option . $this->whereTo($where) . $this->addChar($value, 1);
            endif;
            // 当第三个参数不存在
            if (is_null($value)) {
                $this->where .= $option . '=' . $this->addChar($where, 1);
            } else if (is_null($where)) {
                // 当第二个参数不存在
                $this->where .= $option;
            }
        } else if (is_array($option)) {     // 当第一个参数为数组
            $qz = "(";

            foreach ($option as $v) {
                // 当第一个参数循环后为数组
                if (is_array($v)) {
                    if (strstr($this->where, '(')) {
                        $qz = ' ';
                    }
                    if (isset($useWhere)) {
                        $qz = '(';
                        unset($useWhere);
                    }
                    $condition = $qz . $this->addChar($v[0], 'where') . ' ' . $v[1] . ' ' . $this->addChar($v[2], 1);
                } else {
                    $this->where .= ' ' . $this->addChar($option[0]) . $option[1] . $option[2];
                    $cc = 1;
                    break;
                }
                $logIc = isset($v[3]) ? ' ' . $v[3] : ' AND';
                $this->where .= isset($mark) ? $logIc . $condition : $condition;
                $mark = 1;
            }
            if (!isset($cc)) {
                $this->where .= ')';
            }
        }
        return $this;
    }

    private function whereTo($field)
    {
        switch ($field) {
            case ($field == 'neq' or $field == '!='):
                return '!=';
            case ($field == 'eq' or $field == '='):
                return '=';
            case ($field == 'like' or $field == '%'):
                return 'LIKE';
            default:
                return $field;
        }
    }

    /**
     * 设置条件
     * @param string $option
     * @param string | array $value
     * @return $this
     */
    public function whereIn($option, $value, $tj = 'AND')
    {
        if ($this->clear > 0) {
            $this->clear();
        }

        // 判断之前是否使用where语句
        if (strpos($this->where, 'WHERE')) {
            $this->where .= ' ' . $tj . ' ';
            $useWhere = 1;
        } else {
            $this->where = ' WHERE ';
        }
        $arr = explode(',', $value);
        $str = '';
        foreach ($arr as $v) {
            $str .= $this->addChar($v, 1) . ',';
        }
        $str = rtrim($str, ',');

        // 判断第一个参数为字符
        if (is_string($value)) {
            $this->where .= $option . " IN (" . $str . ")";
        } else if (is_array($value)) {
            $str = '';
            foreach ($value as $v) {
                $str .= $this->addChar($v, 1) . ',';
            }
            $str = rtrim($str, ',');
            $this->where .= $option . " IN (" . $str . ")";
        }
        return $this;
    }

    /**
     * 设置条件
     * @param $option
     * @param string $where
     * @param string $value
     * @return $this
     */
    public function whereOr($option, $where = null, $value = null)
    {
        if ($this->clear > 0) {
            $this->clear();
        }

        if (strpos($this->where, 'WHERE')) {
            $this->where .= ' OR ';
            $ss = 1;
        } else {
            $this->where = ' WHERE ';
        }

        if (is_string($option)) {
            if (!is_null($value)):
                $this->where .= $option . $this->whereTo($where) . $this->addChar($value, 1);
            endif;

            if (is_null($value)) {
                $this->where .= $option . '=' . $this->addChar($where, 1);
            } else if (is_null($where)) {
                $this->where .= $option;
            }
        } else if (is_array($option)) {
            $qz = '(';
            foreach ($option as $v) {
                $logIc = ' AND';
                if (is_array($v)) {
                    if (strstr($this->where, '(')) {
                        $qz = ' ';
                    }
                    if (isset($ss)) {
                        $qz = '(';
                        unset($ss);
                    }
                    $condition = $qz . $this->addChar($v[0]) . ' ' . $v[1] . ' ' . $this->addChar($v[2], 1);
                } else {
                    $this->where .= ' ' . $this->addChar($option[0]) . $option[1] . $option[2];
                    $cc = 1;
                    break;
                }
                if (isset($v[3]) and ($v[3] == 'or' or $v[3] == 'OR')) {
                    $logIc = ' OR';
                    $this->where .= isset($mark) ? $logIc . $condition : $condition;
                } else {
                    $this->where .= isset($mark) ? $logIc . $condition : $condition;
                }

                $mark = 1;
            }
            if (!isset($cc)) {
                $this->where .= ')';
            }

        }

        return $this;
    }

    /**
     * 取得数据表的字段信息
     * @return array
     */
    public function tbFields()
    {
        $sql = 'SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME="' . str_replace('`', '', self::$table) . '" AND TABLE_SCHEMA="' . $this->dbName . '"';
        $res = $this->doQuery($sql);

        $ret = array();
        foreach ($res as $key => $value) {
            $ret[] = $value['COLUMN_NAME'];
        }
        return $ret;
    }

    /**
     * 过滤并格式化数据表字段
     * @param $data
     * @return array
     */
    public function dataFormat($data)
    {
        if (!is_array($data)) {
            return [];
        }

        $table_column = $this->tbFields();
        $ret = [];
        foreach ($data as $key => $val):
            if (!is_scalar($val)) {
                continue;
            }

            if (array_key_exists($key, $table_column)):
                $key = $this->addChar($key);
                if (is_int($val)) {
                    $val = intval($val);
                } else if (is_float($val)) {
                    $val = floatval($val);
                } else if (preg_match('/^\(\w*(\+|\-|\*|\/)?\w*\)$/i', $val)) {
                    $val = $val;
                } elseif (is_string($val)) {
                    $val = '"' . addslashes($val) . '"';
                }
                $ret[$key] = $val;
            endif;
        endforeach;

        return $ret;
    }

    /**
     * 排序
     * @param $option
     * @param null $sort
     * @return $this
     */
    public function order($option, $sort = null)
    {
        if ($this->clear > 0) {
            $this->clear();
        }

        $this->order = ' ORDER BY ';
        if (!is_null($sort)) {
            $this->order .= $option . ' ' . $sort;
        } else if (is_string($option)) {
            $this->order .= $option;
        } else if (is_array($option)) {
            foreach ($option as $k => $v) {
                $order = $k . " " . $v;
                $this->order .= isset($mark) ? ',' . $order : $order;
                $mark = 1;
            }
        }
        return $this;
    }

    /**
     * @param $option
     * @return $this
     */
    public function group($option)
    {
        if ($this->clear > 0) {
            $this->clear();
        }

        $this->group = ' GROUP BY ' . $option;

        return $this;
    }

    /**
     * 分页
     * @param $page
     * @param null $pageSize
     * @return $this
     */
    public function limit($page, $pageSize = null)
    {
        if ($this->clear > 0) {
            $this->clear();
        }

        if ($pageSize === null) {
            $this->limit = 'LIMIT ' . $page;
        } else {
            $pagEval = intval(($page - 1) * $pageSize);
            $this->limit = 'LIMIT ' . $pagEval . ',' . $pageSize;
        }
        return $this;
    }

    /**
     * 设置字段名
     * @param $field
     * @return $this
     */
    public function field($field)
    {
        if ($this->clear > 0) {
            $this->clear();
        }
        $this->field = $field;
        return $this;
    }

    /**
     * 查询 左右内全
     * @param $tab
     * @param string $where
     * @param string $join
     * @return $this
     */
    public function join($tab, $where = '', $join = 'INNER')
    {
        if ($this->clear > 0) {
            $this->clear();
        }
        if (is_array($tab)) {
            foreach ($tab as $k => $v):
                $table = $k . ' AS ' . $v;
            endforeach;
        } else {
            $table = str_replace(' ', ' AS ', $tab);
        }
        self::$table .= ' ' . $join . ' JOIN ' . $table . ' ON(' . $where . ')';

        return $this;
    }

    /**
     * 计数
     * @return mixed
     */
    public function count()
    {
        if ($this->clear > 0) {
            $this->clear();
        }
        $sql = 'SELECT count(' . trim($this->field) . ') AS ' . trim($this->field) . ' FROM ' . self::$table . ' ' . trim($this->where) . " " . trim($this->order);
        $rows = $this->doQuery($sql, false);
        return $rows[trim($this->field)];
    }

    /**
     * 统计
     * @return mixed
     */
    public function sum()
    {
        if ($this->clear > 0) {
            $this->clear();
        }
        $sql = 'SELECT SUM(' . trim($this->field) . ') AS ' . trim($this->field) . ' FROM ' . self::$table . ' ' . trim($this->where) . " " . trim($this->order);
        $rows = $this->doQuery($sql, false);
        return $rows[trim($this->field)];
    }

    /**
     * 清理标记函数
     */
    private function clear()
    {
        $this->where = '';
        $this->order = '';
        $this->limit = '';
        $this->field = '*';
        $this->clear = 0;
    }

    /**
     * 手动清理标记
     * @return $this
     */
    public function clearKey()
    {
        $this->clear();
        return $this;
    }

    /**
     * 启动事务
     */
    public function startTrans()
    {
        //数据rollback 支持
        if (self::$trans == 0) {
            self::$db->beginTransaction();
        }

        self::$trans++;
        return;
    }

    /**
     * 用于非自动提交状态下面的查询提交
     * @return bool
     */
    public function commit()
    {
        $result = true;
        if (self::$trans > 0) {
            $result = self::$db->commit();
            self::$trans = 0;
        }
        return $result;
    }

    /**
     * 事务回滚
     * @return bool
     */
    public function rollback()
    {
        $result = true;
        if (self::$trans > 0) {
            $result = self::$db->rollback();
            self::$trans = 0;
        }
        return $result;
    }

    /**
     * 关闭连接
     */
    public function close()
    {
        if (!is_null(self::$db)) {
            self::$db = null;
        }

    }

}
Licensed under CC BY-NC-SA 4.0
最后更新于 Aug 15, 2025 15:01 +0800