-
Notifications
You must be signed in to change notification settings - Fork 4
/
zpdo.php
377 lines (323 loc) · 10.5 KB
/
zpdo.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
<?php
/**
* User: shenzhe
* Date: 13-6-17
*/
class zpdo
{
/**
* @var \PDO
*/
private $pdo;
private $dbName;
private $tableName;
private $className;
private $config;
private $lastTime;
private $lastSql;
/**
* @param $config
* @param null $className
* entityDemo
* <?php
* 假设数据库有user表,表含有id(自增主键), username, password三个字段
* class UserEntity {
* const TABLE_NAME = 'user'; //对应的数据表名
* const PK_ID = 'id'; //主键id名
* public $id; //public属性与表字段一一对应
* public $username;
* public $password;
* }
* @param null $dbName
* return zpdo
*/
public function __construct($config, $className = null, $dbName = null)
{
$this->config = $config;
if(empty($this->config['pingtime'])) {
$this->config['pingtime'] = 3600;
}
if (!empty($className)) {
$this->className = $className;
}
if (empty($dbName)) {
$this->dbName = $config['dbname'];
} else {
$this->dbName = $dbName;
}
$this->lastTime = time() + $this->config['pingtime'];
$this->checkPing();
}
public function checkPing()
{
if (empty($this->pdo)) {
$this->pdo = $this->connect();
} elseif (!empty($this->config['ping'])) {
$this->ping();
}
}
private function connect()
{
return new \PDO($this->config['dsn'], $this->config['user'], $this->config['pass'], array(
\PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES '{$this->config['charset']}';",
\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,
\PDO::ATTR_PERSISTENT => empty($this->config['pconnect']) ? 0 : 1
));
}
public function getDBName()
{
return $this->dbName;
}
public function setDBName($dbName)
{
if (empty($dbName)) {
return;
}
$this->dbName = $dbName;
}
//add set TableName change by ahuo 2013-11-05 14:23
public function setTableName($tableName)
{
if(empty($tableName)){
return;
}
$this->tableName = $tableName;
}
public function getTableName()
{
if (empty($this->tableName)) {
if(method_exists($this->className, 'getTableName')) {
$this->tableName = call_user_func(array($this->className, 'getTableName'));
} else {
$entityRef = new \ReflectionClass($this->className);
$this->tableName = $entityRef->getConstant('TABLE_NAME');
}
}
return $this->tableName;
}
public function setClassName($className)
{
if (!empty($className) && $this->className != $className) {
$this->className = $className;
$this->tableName = null;
}
}
public function getClassName()
{
return $this->className;
}
public function getLibName()
{
return "`{$this->getDBName()}`.`{$this->getTableName()}`";
}
public function getPdo()
{
return $this->pdo;
}
public function setPdo($pdo)
{
$this->pdo = $pdo;
}
public function add($entity, $fields, $onDuplicate = null)
{
$strFields = '`' . implode('`,`', $fields) . '`';
$strValues = ':' . implode(', :', $fields);
$query = "INSERT INTO {$this->getLibName()} ({$strFields}) VALUES ({$strValues})";
if (!empty($onDuplicate)) {
$query .= 'ON DUPLICATE KEY UPDATE ' . $onDuplicate;
}
$statement = $this->pdo->prepare($query);
$this->lastSql = $query;
$params = array();
foreach ($fields as $field) {
$params[$field] = $entity->$field;
}
$statement->execute($params);
return $this->pdo->lastInsertId();
}
public function addMulti($entitys, $fields)
{
$items = array();
$params = array();
foreach ($entitys as $index => $entity) {
$items[] = '(:' . implode($index . ', :', $fields) . $index . ')';
foreach ($fields as $field) {
$params[$field . $index] = $entity->$field;
}
}
$query = "INSERT INTO {$this->getLibName()} (`" . implode('`,`', $fields) . "`) VALUES " . implode(',', $items);
$statement = $this->pdo->prepare($query);
$this->lastSql = $query;
$statement->execute($params);
return $statement->rowCount();
}
public function replace($entity, $fields)
{
$strFields = '`' . implode('`,`', $fields) . '`';
$strValues = ':' . implode(', :', $fields);
$query = "REPLACE INTO {$this->getLibName()} ({$strFields}) VALUES ({$strValues})";
$statement = $this->pdo->prepare($query);
$this->lastSql = $query;
$params = array();
foreach ($fields as $field) {
$params[$field] = $entity->$field;
}
$statement->execute($params);
return $this->pdo->lastInsertId();
}
public function update($fields, $params, $where, $change = false)
{
if ($change) {
$updateFields = array_map(__CLASS__ . '::changeFieldMap', $fields);
} else {
$updateFields = array_map(__CLASS__ . '::updateFieldMap', $fields);
}
$strUpdateFields = implode(',', $updateFields);
$query = "UPDATE {$this->getLibName()} SET {$strUpdateFields} WHERE {$where}";
$statement = $this->pdo->prepare($query);
$this->lastSql = $query;
$statement->execute($params);
return $statement->rowCount();
}
public function fetchValue($where = '1', $params = null, $fields = '*')
{
$query = "SELECT {$fields} FROM {$this->getLibName()} WHERE {$where} limit 1";
$statement = $this->pdo->prepare($query);
$this->lastSql = $query;
$statement->execute($params);
return $statement->fetchColumn();
}
public function fetchArray($where = '1', $params = null, $fields = '*', $orderBy = null, $limit = null)
{
$query = "SELECT {$fields} FROM {$this->getLibName()} WHERE {$where}";
if ($orderBy) {
$query .= " ORDER BY {$orderBy}";
}
if ($limit) {
$query .= " limit {$limit}";
}
$statement = $this->pdo->prepare($query);
$this->lastSql = $query;
$statement->execute($params);
$statement->setFetchMode(\PDO::FETCH_ASSOC);
return $statement->fetchAll();
}
public function fetchCol($where = '1', $params = null, $fields = '*', $orderBy = null, $limit = null)
{
$results = $this->fetchArray($where, $params, $fields, $orderBy, $limit);
return empty($results) ? array() : array_map('reset', $results);
}
public function fetchAll($where = '1', $params = null, $fields = '*', $orderBy = null, $limit = null)
{
$query = "SELECT {$fields} FROM {$this->getLibName()} WHERE {$where}";
if ($orderBy) {
$query .= " order by {$orderBy}";
}
if ($limit) {
$query .= " limit {$limit}";
}
$statement = $this->pdo->prepare($query);
$this->lastSql = $query;
if (!$statement->execute($params)) {
throw new \Exception('data base error');
}
if($this->className) {
$statement->setFetchMode(\PDO::FETCH_CLASS, $this->className);
} else {
$statement->setFetchMode(\PDO::FETCH_ASSOC);
}
return $statement->fetchAll();
}
public function fetchEntity($where = '1', $params = null, $fields = '*', $orderBy = null)
{
$query = "SELECT {$fields} FROM {$this->getLibName()} WHERE {$where}";
if ($orderBy) {
$query .= " order by {$orderBy}";
}
$query .= " limit 1";
$statement = $this->pdo->prepare($query);
$this->lastSql = $query;
$statement->execute($params);
if($this->className) {
$statement->setFetchMode(\PDO::FETCH_CLASS, $this->className);
} else {
$statement->setFetchMode(\PDO::FETCH_ASSOC);
}
return $statement->fetch();
}
public function fetchCount($where = '1', $pk = "*")
{
$query = "SELECT count({$pk}) as count FROM {$this->getLibName()} WHERE {$where}";
$statement = $this->pdo->prepare($query);
$this->lastSql = $query;
$statement->execute();
$result = $statement->fetch();
return $result["count"];
}
//$params = [] php5.3.6 报语法错误 change by ahuo 2013-11-05 14:23
public function remove($where, $params = array())
{
if (empty($where)) {
return false;
}
$query = "DELETE FROM {$this->getLibName()} WHERE {$where}";
$statement = $this->pdo->prepare($query);
$statement->execute($params);
$this->lastSql = $query;
return $statement->rowCount();
}
public function flush()
{
$query = "TRUNCATE {$this->getLibName()}";
$statement = $this->pdo->prepare($query);
$this->lastSql = $query;
return $statement->execute();
}
public static function updateFieldMap($field)
{
return '`' . $field . '`=:' . $field;
}
public static function changeFieldMap($field)
{
return '`' . $field . '`=`' . $field . '`+:' . $field;
}
public function fetchBySql($sql)
{
$statement = $this->pdo->prepare($sql);
$this->lastSql = $sql;
$statement->execute();
$statement->setFetchMode(\PDO::FETCH_ASSOC);
return $statement->fetchAll();
}
public function ping()
{
$now = time();
if($this->lastTime < $now) {
if (empty($this->pdo)) {
$this->pdo = $this->connect();
} else {
try {
$status = $this->pdo->getAttribute(\PDO::ATTR_SERVER_INFO);
} catch (\Exception $e) {
if ($e->getCode() == 'HY000') {
$this->pdo = $this->connect();
} else {
throw $e;
}
}
}
}
$this->lastTime = $now + $this->config['pingtime'];
return $this->pdo;
}
public function close()
{
if(empty($this->config['pconnect'])) {
$this->pdo = null;
}
}
public function getLastSql()
{
return $this->lastSql;
}
}