-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpdo.class.php
718 lines (501 loc) · 18.1 KB
/
pdo.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
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
<?php
/**
* PDO操作类
* 说明 : 如果要使用 getAllWithPage()方法则必须要引入分页类
*
*/
class pdoModel{
//pdo对象
private $_pdo;
//数据库名称
private $_name;
//最后执行的sql
protected $_lastExecSql;
//最后插入的ID
protected $_lastInsertId;
/**
* 根据数据库配置参数 初始化PDO对象
*
* @param array $DB_CONFIG 数据库配置参数
* @return object $pdo 返回实例化后的PDO对象
*/
function __construct( $DB_CONFIG = array() ) {
if ( empty($DB_CONFIG) ) {
echo 'ERROR: DB_CONFIG array is empty';
die();
}
//拼接字符串
$pdoDSN = '';
$pdoDSN = "mysql:dbname={$DB_CONFIG['DB_NAME']};host={$DB_CONFIG['DB_HOST']};port={$DB_CONFIG['DB_PORT']};";
//记录数据库名称
$_name = $DB_CONFIG['DB_NAME'];
try {
$pdo = NULL;
//实例化PDO对象
$pdo = new PDO($pdoDSN, $DB_CONFIG['DB_USER'], $DB_CONFIG['DB_PWD'], $DB_CONFIG['DB_OPTIONS']);
//设置数据库编码
$pdo->exec(" SET NAMES '{$DB_CONFIG['DB_CHARSET']}' ");
$this->_pdo = $pdo;
} catch (PDOException $e) {
echo 'Init PDO ERROR: ' . $e->getMessage();
die();
}
}
/**
* 获取pdo对象
*
* @return Object $pdo 获取pdo对象
*/
public function getPDOInstance(){
return $this->_pdo;
}
/**
* 获取最后新增的id
*
* @return integer $id 获取最后新增的id
*/
public function lastInsertId(){
return $this->_pdo->lastInsertId();
}
/**
* 获取最后执行的sql语句
*
* @return string $sql 最后执行的sql语句
*/
public function getLastSql(){
return $this->_lastExecSql;
}
/**
* 带分页的查询
*
* @param string $searchSql 查询sql语句
* @param integer $rows 每页显示条数
* @param string $params 额外附加参数,例如 : &uid=1001
* @param boolean $debug 是否开启调试模式,开始调试模式直接返回sql
* @return array $result 返回结果
*/
public function getAllWithPage($searchSql = '' , $rows = 10 , $params = '' , $debug = false ){
$debugInfo = array();
$result = array();
if( empty($searchSql) ){
return $result;
}
$total = 0;
$total = $this->getCount($searchSql);
if( intval($total) <= 0 ){
return $result;
}
//加载分页类
require_once __DIR__.DIRECTORY_SEPARATOR.'pageModel.class.php';
//实例化分页类
$pageModel = new pageModel($total , $rows , $params);
$searchPageSql = $searchSql . $pageModel->limit;
//开启调试模式
if( true === $debug ){
$debugInfo['searchSql'] = $searchSql;
$debugInfo['listSql'] = $searchPageSql;
//显示分页信息
$debugInfo['pageStr'] = $pageModel->showPage();
return $debugInfo;
}
$list = array();
$list = $this->getAll($searchPageSql);
$result['total'] = $total;
$result['pageStr'] = $pageModel->showPage();
$result['list'] = $list;
return $result;
}
/**
* 自动替换查询条件中的统计语句
*
* @param string $searchSql 查询sql语句
* @param boolean $debug 是否开启调试模式
* @return integer $count 查询数量
*/
public function getCount($searchSql = '' , $debug = false ){
if( empty($searchSql) ) {
return 0;
}
try{
//检测 最后一个 FROM 所在字符串中位置
$fromStrPosition = strripos( trim($searchSql) ,' FROM ');
if( intval($fromStrPosition) <= 0 ){
return 0;
}
//替换最后一个 FROM 之前的查询语句
$countSqlStr = substr_replace( trim($searchSql) , ' SELECT count(*) AS count FROM ', 0 , $fromStrPosition + 6 );
$count = $this->getColumn($countSqlStr,$debug);
return intval($count);
} catch (Exception $e){
echo " GET COUNT ERROR : ".$e->getMessage();
die();
}
}
/**
* 自动替换查询条件中的统计语句
*
* @param string $searchSql 查询sql语句
* @param boolean $debug 是否开启调试模式
* @return integer $count 查询数量
*/
public function getCount2($searchSql = '' , $debug = false ){
if( empty($searchSql) ) {
return 0;
}
try{
/* //检测 最后一个 FROM 所在字符串中位置
$fromStrPosition = strripos( trim($searchSql) ,' FROM ');
if( intval($fromStrPosition) <= 0 ){
return 0;
}
//替换最后一个 FROM 之前的查询语句
$countSqlStr = substr_replace( trim($searchSql) , ' SELECT count(*) AS count FROM ',0 , $fromStrPosition + 6);*/
$count = $this->getColumn($searchSql,$debug);
return intval($count);
} catch (Exception $e){
echo " GET COUNT ERROR : ".$e->getMessage();
die();
}
}
/**
* 查询所有记录
*
* @param string $searchSql sql查询语句
* @param boolean $debug 是否开启调试模式,开始调试模式直接返回sql
* @return array $result 查询结果
*/
public function getAll( $searchSql = '' , $debug = false){
if( empty($searchSql) ) {
return NULL;
}
if(true === $debug) {
return $searchSql;
}
try {
//执行sql预处理
$sth = $this->_pdo->prepare($searchSql);
$execResult = $sth->execute();
if( false === $execResult ){
return NULL;
}
$result = $sth->fetchAll(PDO::FETCH_ASSOC);
$this->_lastExecSql = $searchSql;
return $result;
} catch (Exception $e) {
//捕获异常信息
echo " GET ALL ERROR : ".$e->getMessage();
die();
}
}
/**
* 查询单条记录
*
* @param string $searchSql sql查询语句
* @param boolean $debug 是否开启调试模式,开始调试模式直接返回sql
* @return array $result 查询结果
*/
public function getRow( $searchSql = '' , $debug = false){
if( empty($searchSql) ) {
return NULL;
}
if(true === $debug) {
return $searchSql;
}
try {
//执行sql预处理
$sth = $this->_pdo->prepare($searchSql);
$execResult = $sth->execute();
if( false === $execResult ){
return NULL;
}
$result = $sth->fetch(PDO::FETCH_ASSOC);
$this->_lastExecSql = $searchSql;
return $result;
} catch (Exception $e) {
//捕获异常信息
echo " GET ROW ERROR : ".$e->getMessage();
die();
}
}
/**
* 查询单个字段数值
*
* @param string $searchSql sql查询语句
* @param boolean $debug 是否开启调试模式,开始调试模式直接返回sql
* @return mixed $result 查询结果
*/
public function getColumn( $searchSql = '' , $debug = false){
if( empty($searchSql) ) {
return NULL;
}
if(true === $debug) {
return $searchSql;
}
try {
//执行sql预处理
$sth = $this->_pdo->prepare($searchSql);
$execResult = $sth->execute();
if( false === $execResult ){
return NULL;
}
$result = $sth->fetchColumn();
$this->_lastExecSql = $searchSql;
return $result;
} catch (Exception $e) {
//捕获异常信息
echo " GET COLUMN ERROR : ".$e->getMessage();
die();
}
}
/**
* 新增数据
*
* @param string $tableName 数据库表名称
* @param array $insertDataArr 新增数据数组
* @param boolean $debug 是否开启调试模式,开始调试模式直接返回sql
* @return integer $rows 返回影响记录的行数,如果发生错误返回false
*/
public function insert($tableName = '' , $insertDataArr = array() , $debug = false){
//如果表名或者插入数据为空,则直接返回0
if( empty($tableName) || empty($insertDataArr) ) {
return false;
}
//开启debug调试模式,则直接输出sql语句
if(true === $debug){
$debugSql = "INSERT INTO `$tableName` (`".implode('`,`', array_keys($insertDataArr))."`) VALUES ('".implode("','", $insertDataArr)."')";
return $debugSql;
}
$bindValueStr = '';
foreach ( array_keys($insertDataArr) as $k => $val) {
if( $k > 0 ){
$bindValueStr .= ", :$val ";
}else{
$bindValueStr .= " :$val ";
}
}
$insertSql = '';
$insertSql = "INSERT INTO `{$tableName}` (`".implode('`,`', array_keys($insertDataArr) )."`) VALUES ( $bindValueStr ) ";
try {
//预处理sql
$sth = $this->_pdo->prepare($insertSql);
foreach ($insertDataArr as $key => &$value) {
$sth->bindParam(":$key", $value);
}
//执行sql语句
$execResult = $sth->execute();
// 预留错误调试 prepare
// $debugInfo = $sth->debugDumpParams();
if($execResult == false) {
return false;
}
//获取受影响行数
$rows = $sth->rowCount();
//获取新增的id
$insertId = $this->_pdo->lastInsertId();
$this->_lastInsertId = $insertId;
//获取最后执行的sql
$this->_lastExecSql = $insertSql;
return $rows;
} catch (Exception $e) {
//捕获异常信息
echo " EXEC ERROR : ".$e->getMessage();
die();
}
}
/**
* 新增或者数据
*
* @param string $tableName 数据库表名称
* @param array $insertDataArr 新增数据数组
* @param boolean $debug 是否开启调试模式,开始调试模式直接返回sql
* @return integer $rows 返回影响记录的行数,如果发生错误返回false
*/
public function replace($tableName = '' , $insertDataArr = array() , $debug = false){
//如果表名或者插入数据为空,则直接返回0
if( empty($tableName) || empty($insertDataArr) ) {
return false;
}
//开启debug调试模式,则直接输出sql语句
if(true === $debug){
$debugSql = "REPLACE INTO `$tableName` (`".implode('`,`', array_keys($insertDataArr))."`) VALUES ('".implode("','", $insertDataArr)."')";
return $debugSql;
}
$bindValueStr = '';
foreach ( array_keys($insertDataArr) as $k => $val) {
if( $k > 0 ){
$bindValueStr .= ", :$val ";
}else{
$bindValueStr .= " :$val ";
}
}
$insertSql = '';
$insertSql = "REPLACE INTO `{$tableName}` (`".implode('`,`', array_keys($insertDataArr) )."`) VALUES ( $bindValueStr ) ";
try {
//预处理sql
$sth = $this->_pdo->prepare($insertSql);
foreach ($insertDataArr as $key => &$value) {
$sth->bindParam(":$key", $value);
}
//执行sql语句
$execResult = $sth->execute();
// 预留错误调试 prepare
// $debugInfo = $sth->debugDumpParams();
if($execResult == false) {
return false;
}
//获取受影响行数
$rows = $sth->rowCount();
return $rows;
} catch (Exception $e) {
//捕获异常信息
echo " EXEC ERROR : ".$e->getMessage();
die();
}
}
/**
* 更新数据
*
* @param string $tableName 数据库表名称
* @param array $updateDataArr 新增数据数组
* @param string $whereSql where限制语句,不能为空(防止误操作),为空直接返回false
* @param boolean $debug 是否开启调试模式,开始调试模式直接返回sql
* @return integer $rows 返回影响记录的行数,如果发生错误返回false
*/
public function update($tableName , $updateDataArr , $whereSql , $debug = false){
if( empty($tableName) || empty($updateDataArr) || empty($whereSql) ){
return false;
}
$updateSqlStr = '';
foreach ($updateDataArr as $key => $value) {
$updateSqlStr .= ", `$key`='$value'";
}
$updateSqlStr = substr($updateSqlStr, 1);
$updateSqlStr = "UPDATE `$tableName` SET $updateSqlStr WHERE $whereSql";
$result = $this->exec($updateSqlStr,$debug);
return $result;
}
/**
* 更新数据
*
* @param string $tableName 数据库表名称
* @param array $updateDataArr 新增数据数组
* @param string $whereSql where限制语句,不能为空(防止误操作),为空直接返回false
* @param boolean $debug 是否开启调试模式,开始调试模式直接返回sql
* @return integer $rows 返回影响记录的行数,如果发生错误返回false
*/
public function update2($tableName , $updateDataArr , $whereSql , $debug = false){
if( empty($tableName) || empty($updateDataArr) || empty($whereSql) ){
return false;
}
//开启debug调试模式,则直接输出sql语句
if(true === $debug){
$debugSql = '';
foreach ($updateDataArr as $key => $value) {
$debugSql .= ", $key = '$value' ";
}
$debugSql = substr($debugSql, 1);
$debugSql = "UPDATE `$tableName` SET $debugSql WHERE $whereSql";
return $debugSql;
}
$updateSqlStr = '';
foreach ($updateDataArr as $key => $value) {
$updateSqlStr .= ", $key = :$key ";
}
$updateSqlStr = substr($updateSqlStr, 1);
$updateSqlStr = "UPDATE `$tableName` SET $updateSqlStr WHERE $whereSql";
try {
//预处理sql
$sth = $this->_pdo->prepare($updateSqlStr);
foreach ($updateDataArr as $key => &$value) {
$sth->bindParam(":$key", $value);
}
//执行sql语句
$execResult = $sth->execute();
// 预留错误调试 prepare
// $debugInfo = $sth->debugDumpParams();
if($execResult == false) {
return false;
}
//获取受影响行数
$rows = $sth->rowCount();
return $rows;
} catch (Exception $e) {
//捕获异常信息
echo " EXEC ERROR : ".$e->getMessage();
die();
}
}
/**
* 执行sql语句 (仅限于新增、修改、删除)
*
* @param string $execSql 执行的sql语句
* @param boolean $debug 是否开启调试模式,开始调试模式直接返回sql
* @return integer $rows 返回操作受影响的行数
*/
public function exec($execSql , $debug = false ){
if( empty($execSql) ){
return false;
}
if( true === $debug ){
return $execSql;
}
try {
//预处理sql
$sth = $this->_pdo->prepare($execSql);
$execResult = $sth->execute();
if($execResult == false) {
return false;
}
//获取受影响行数
$rows = $sth->rowCount();
//获取最后执行的sql
$this->_lastExecSql = $execSql;
return $rows;
} catch (Exception $e) {
//捕获异常信息
echo " ERROR : ".$e->getMessage();
die();
}
}
/**
* beginTransaction 事务开始
*/
public function beginTransaction(){
$this->_pdo->beginTransaction();
}
/**
* commit 事务提交
*/
public function commit(){
$this->_pdo->commit();
}
/**
* rollback 事务回滚
*/
public function rollback(){
$this->_pdo->rollback();
}
/**
* 检测连接是否存在
*/
public function checkPing(){
try{
$this->_pdo->getAttribute(PDO::ATTR_SERVER_INFO);
} catch (PDOException $e) {
if( strpos($e->getMessage(), 'MySQL server has gone away') !== false ){
return false;
}
}
return true;
}
/**
* 关闭PDO连接
*
*/
public function close(){
$this->_pdo = NULL;
$this->_name = '';
$this->_lastInsertId = 0;
$this->_lastExecSql = '';
}
}