-
-
Notifications
You must be signed in to change notification settings - Fork 41
/
Copy pathPDO.php
100 lines (85 loc) · 2.57 KB
/
PDO.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
<?php
/**
*
* This file is part of mvc-rest-api for PHP.
*
*/
namespace Database\DB;
/**
* Global Class PDO
*/
final class PDO {
/**
* @var
*/
private $pdo = null;
/**
* @var
*/
private $statement = null;
/**
* Construct, create opject of PDO class
*/
public function __construct($hostname, $username, $password, $database, $port) {
try {
$this->pdo = new \PDO("mysql:host=" . $hostname . ";port=" . $port . ";dbname=" . $database, $username, $password, array(\PDO::ATTR_PERSISTENT => true));
} catch(\PDOException $e) {
trigger_error('Error: Could not make a database link ( ' . $e->getMessage() . '). Error Code : ' . $e->getCode() . ' <br />');
exit();
}
// set default setting database
$this->pdo->exec("SET NAMES 'utf8'");
$this->pdo->exec("SET CHARACTER SET utf8");
$this->pdo->exec("SET CHARACTER_SET_CONNECTION=utf8");
$this->pdo->exec("SET SQL_MODE = ''");
}
/**
* exec query statement
*/
public function query($sql) {
$this->statement = $this->pdo->prepare($sql);
$result = false;
try {
if ($this->statement && $this->statement->execute()) {
$data = array();
while ($row = $this->statement->fetch(\PDO::FETCH_ASSOC)) {
$data[] = $row;
}
// create std class
$result = new \stdClass();
$result->row = (isset($data[0]) ? $data[0] : array());
$result->rows = $data;
$result->num_rows = $this->statement->rowCount();
}
} catch (\PDOException $e) {
trigger_error('Error: ' . $e->getMessage() . ' Error Code : ' . $e->getCode() . ' <br />' . $sql);
exit();
}
if ($result) {
return $result;
} else {
$result = new \stdClass();
$result->row = array();
$result->rows = array();
$result->num_rows = 0;
return $result;
}
}
/**
* claen data
*/
public function escape($value) {
$search = array("\\", "\0", "\n", "\r", "\x1a", "'", '"');
$replace = array("\\\\", "\\0", "\\n", "\\r", "\Z", "\'", '\"');
return str_replace($search, $replace, $value);
}
/**
* return last id insert
*/
public function getLastId() {
return $this->pdo->lastInsertId();
}
public function __destruct() {
$this->pdo = null;
}
}