-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmysqli_cached.php
168 lines (95 loc) · 3.1 KB
/
mysqli_cached.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
<?php
namespace DB;
final class MySQLi_Cached {
private $link;
private $cache;
private $cachedquery;
public function __construct($hostname, $username, $password, $database, $port = '3306') {
$this->cache = new Cache(DB_CACHED_EXPIRE);
$this->link = new \mysqli($hostname, $username, $password, $database, $port);
if ($this->link->connect_error) {
trigger_error('Error: Could not make a database link (' . $this->link->connect_errno . ') ' . $this->link->connect_error);
exit();
}
$this->link->set_charset("utf8");
$this->link->query("SET SQL_MODE = ''");
$this->link->query("SET NAMES 'utf-8");
$this->link->query("SET CHARACTER_SET_CONNECTION=utf8");
}
public function query($sql) {
// Only SELECT query
// COMMENTS HERE
// COMMENTS HERE
// COMMENTS HERE
$isselect = 0;
$md5query = '';
$pos = stripos($sql, 'select ');
if ($pos == 0)
{
$isselect = 1;
$md5query = md5($sql);
if ($query = $this->cache->get('sql_' . $md5query)) {
if ($query->sql == $sql) {
if ($resetflag = $this->cache->get('sql_globalresetcache')) {
if ($resetflag <= $query->time) {
$this->cachedquery = $query;
return($query);
}
else {
$this->cachedquery = $query;
return($query);
}
}
}
}
$resource = $this->link->query($sql);
if ($resource) {
if (is_resource($resource)) {
$i = 0;
$data = array;
while ($result = $query->fetch_accoc($resource)) {
$data[$i] = $result;
$i++;
}
}
}
}
$query = $this->link->query($sql);
if (!$this->link->errno) {
if ($query instanceof \mysqli_result) {
$data = array();
while ($row = $query->fetch_assoc()) {
$data[] = $row;
}
$result = new \stdClass();
$result->num_rows = $query->num_rows;
$result->row = isset($data[0]) ? $data[0] : array();
$result->rows = $data;
$query->close();
return $result;
} else {
return true;
}
} else {
trigger_error('Error: ' . $this->link->error . '<br />Error No: ' . $this->link->errno . '<br />' . $sql);
}
}
public function escape($value) {
return $this->link->real_escape_string($value);
}
public function countAffected() {
if(isset($this->cachedquery) && $this->cachedquery)
{
return $this->cachedquery->num_rows;
}
else {
return $this->link->affected_rows;
}
}
public function getLastId() {
return $this->link->insert_id;
}
public function __destruct() {
$this->link->close();
}
}