Use object oriented MySQLi
[platal.git] / classes / xdb.php
1 <?php
2 /***************************************************************************
3 * Copyright (C) 2003-2007 Polytechnique.org *
4 * http://opensource.polytechnique.org/ *
5 * *
6 * This program is free software; you can redistribute it and/or modify *
7 * it under the terms of the GNU General Public License as published by *
8 * the Free Software Foundation; either version 2 of the License, or *
9 * (at your option) any later version. *
10 * *
11 * This program is distributed in the hope that it will be useful, *
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
14 * GNU General Public License for more details. *
15 * *
16 * You should have received a copy of the GNU General Public License *
17 * along with this program; if not, write to the Free Software *
18 * Foundation, Inc., *
19 * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *
20 **************************************************************************/
21
22 class XDB
23 {
24 private static $mysqli = null;
25
26 public static function connect($host, $user, $pwd, $db, $charset = 'utf8', $debug = 0)
27 {
28 XDB::$mysqli = new mysqli($host, $user, $pwd, $db);
29 if (mysqli_connect_errno() && $debug & 1) {
30 $GLOBALS['XDB::trace_data'][] = array('query' => 'MySQLI connection', 'explain' => array(),
31 'error' => mysqli_connect_error(), 'exectime' => 0, 'rows' => 0);
32 $GLOBALS['XDB::error'] = true;
33 return false;
34 }
35 XDB::$mysqli->autocommit(true);
36 XDB::$mysqli->set_charset($charset);
37 return true;
38 }
39
40 public static function _prepare($args)
41 {
42 $query = array_map(Array('XDB', '_db_escape'), $args);
43 $query[0] = str_replace('{?}', '%s', str_replace('%', '%%', $args[0]));
44 return call_user_func_array('sprintf', $query);
45 }
46
47 public static function _reformatQuery($query)
48 {
49 $query = preg_split("/\n\\s*/", trim($query));
50 $length = 0;
51 foreach ($query as $key=>$line) {
52 $local = -2;
53 if (preg_match('/^([A-Z]+(?:\s+(?:JOIN|BY|FROM|INTO))?)\s+(.*)/u', $line, $matches)
54 && $matches[1] != 'AND' && $matches[1] != 'OR')
55 {
56 $local = strlen($matches[1]);
57 $line = $matches[1] . ' ' . $matches[2];
58 $length = max($length, $local);
59 }
60 $query[$key] = array($line, $local);
61 }
62 $res = '';
63 foreach ($query as $array) {
64 list($line, $local) = $array;
65 $local = max(0, $length - $local);
66 $res .= str_repeat(' ', $local) . $line . "\n";
67 $length += 2 * (substr_count($line, '(') - substr_count($line, ')'));
68 }
69 return $res;
70 }
71
72 public static function _query($query)
73 {
74 global $globals;
75
76 if ($globals->debug & 1) {
77 $explain = array();
78 if (strpos($query, 'FOUND_ROWS()') === false) {
79 $res = XDB::$mysqli->query("EXPLAIN $query");
80 if ($res) {
81 while ($row = $res->fetch_assoc()) {
82 $explain[] = $row;
83 }
84 $res->free();
85 }
86 }
87 $trace_data = array('query' => XDB::_reformatQuery($query), 'explain' => $explain);
88 $time_start = microtime();
89 }
90
91 $res = XDB::$mysqli->query($query);
92
93 if ($globals->debug & 1) {
94 list($ue, $se) = explode(" ", microtime());
95 list($us, $ss) = explode(" ", $time_start);
96 $time = intval((($ue - $us) + ($se - $ss)) * 1000);
97 $trace_data['error'] = XDB::$mysqli->error;
98 $trace_data['exectime'] = $time;
99 $trace_data['rows'] = @$res->num_rows ? $res->num_rows : XDB::$mysqli->affected_rows;
100 $GLOBALS['XDB::trace_data'][] = $trace_data;
101 if (XDB::$mysqli->errno) {
102 $GLOBALS['XDB::error'] = true;
103 }
104 }
105 return $res;
106 }
107
108 public static function query()
109 {
110 return new XOrgDBResult(XDB::_prepare(func_get_args()));
111 }
112
113 public static function execute()
114 {
115 return XDB::_query(XDB::_prepare(func_get_args()));
116 }
117
118 public static function iterator()
119 {
120 return new XOrgDBIterator(XDB::_prepare(func_get_args()));
121 }
122
123 public static function iterRow()
124 {
125 return new XOrgDBIterator(XDB::_prepare(func_get_args()), MYSQL_NUM);
126 }
127
128 public static function insertId()
129 {
130 return XDB::$mysqli->insert_id;
131 }
132
133 public static function _db_escape($var)
134 {
135 switch (gettype($var)) {
136 case 'boolean':
137 return $var ? 1 : 0;
138
139 case 'integer':
140 case 'double':
141 case 'float':
142 return $var;
143
144 case 'string':
145 return "'".addslashes($var)."'";
146
147 case 'NULL':
148 return 'NULL';
149
150 case 'object':
151 case 'array':
152 return "'".addslashes(serialize($var))."'";
153
154 default:
155 die(var_export($var, true).' is not a valid for a database entry');
156 }
157 }
158
159 public static function trace_format(&$page, $template = 'skin/common.database-debug.tpl') {
160 $page->assign('trace_data', @$GLOBALS['XDB::trace_data']);
161 $page->assign('db_error', @$GLOBALS['XDB::error']);
162 return $page->fetch($template);
163 }
164 }
165
166 class XOrgDBResult
167 {
168
169 private $_res;
170
171 function XOrgDBResult($query)
172 {
173 $this->_res = XDB::_query($query);
174 }
175
176 function free()
177 {
178 $this->_res->free();
179 unset($this);
180 }
181
182 function _fetchRow()
183 {
184 return $this->_res->fetch_row();
185 }
186
187 function _fetchAssoc()
188 {
189 return $this->_res->fetch_assoc();
190 }
191
192 function fetchAllRow()
193 {
194 $result = Array();
195 while ($result[] = $this->_res->fetch_row());
196 array_pop($result);
197 $this->free();
198 return $result;
199 }
200
201 function fetchAllAssoc()
202 {
203 $result = Array();
204 while ($result[] = $this->_res->fetch_assoc());
205 array_pop($result);
206 $this->free();
207 return $result;
208 }
209
210 function fetchOneAssoc()
211 {
212 $tmp = $this->_fetchAssoc();
213 $this->free();
214 return $tmp;
215 }
216
217 function fetchOneRow()
218 {
219 $tmp = $this->_fetchRow();
220 $this->free();
221 return $tmp;
222 }
223
224 function fetchOneCell()
225 {
226 $tmp = $this->_fetchRow();
227 $this->free();
228 return $tmp[0];
229 }
230
231 function fetchColumn($key = 0)
232 {
233 $res = Array();
234 if (is_numeric($key)) {
235 while($tmp = $this->_fetchRow()) {
236 $res[] = $tmp[$key];
237 }
238 } else {
239 while($tmp = $this->_fetchAssoc()) {
240 $res[] = $tmp[$key];
241 }
242 }
243 $this->free();
244 return $res;
245 }
246
247 function numRows()
248 {
249 return $this->_res->num_rows;
250 }
251 }
252
253 class XOrgDBIterator
254 {
255 private $_result;
256 private $_pos;
257 private $_total;
258 private $_mode = MYSQL_ASSOC;
259
260 function __construct($query, $mode = MYSQL_ASSOC)
261 {
262 $this->_result = new XOrgDBResult($query);
263 $this->_pos = 0;
264 $this->_total = $this->_result->numRows();
265 $this->_mode = $mode;
266 }
267
268 function next()
269 {
270 $this->_pos ++;
271 if ($this->_pos > $this->_total) {
272 $this->_result->free();
273 unset($this);
274 return null;
275 }
276 return $this->_mode != MYSQL_ASSOC ? $this->_result->_fetchRow() : $this->_result->_fetchAssoc();
277 }
278
279 function first()
280 {
281 return $this->_pos == 1;
282 }
283
284 function last()
285 {
286 return $this->_last == $this->_total;
287 }
288
289 function total()
290 {
291 return $this->_total;
292 }
293 }
294
295 // vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8:
296 ?>