JasonWoof Got questions, comments, patches, etc.? Contact Jason Woofenden
session_new() returns id, fixed db_count()
[wfpl.git] / db.php
1 <?php
2
3 #  Copyright (C) 2006 Jason Woofenden
4 #
5 #  This file is part of wfpl.
6 #
7 #  wfpl is free software; you can redistribute it and/or modify it under the
8 #  terms of the GNU Lesser General Public License as published by the Free
9 #  Software Foundation; either version 2.1 of the License, or (at your option)
10 #  any later version.
11 #
12 #  wfpl is distributed in the hope that it will be useful, but WITHOUT ANY
13 #  WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
14 #  FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public License for
15 #  more details.
16 #
17 #  You should have received a copy of the GNU Lesser General Public License
18 #  along with wfpl; if not, write to the Free Software Foundation, Inc., 51
19 #  Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
20
21
22 require_once('code/wfpl/encode.php');
23 require_once('code/wfpl/format.php');
24
25 # db_connect() -- connect to a mysql database
26 #
27 # PARAMETERS:
28 #
29 #   database: the name of the database you want to connect to. Defaults to the
30 #   second-to-last part of the domain name. eg for foo.example.com it would be
31 #   "example".
32
33 #   user: username for connecting to the database. Defaults to
34 #   $GLOBALS['db_username'] or (if that's not set) "www".
35
36 #   password: password for connecting to the database. Defaults to
37 #   $GLOBALS['db_password'] or (if that's not set "".
38 #
39 # RETURNS:
40 #
41 #   the database connection handle. You'll only need this if you want to have
42 #   multiple databases open at once.
43
44 function db_connect($database = 'auto', $user = 'auto', $pass = 'auto', $host = 'localhost') {
45         if($database == 'auto') {
46                 if(isset($GLOBALS['db_name'])) {
47                         $database = $GLOBALS['db_name'];
48                 } else {
49                         $host = $_SERVER['SERVER_NAME'];
50                         $host = explode('.', $host);
51                         array_pop($host);
52                         $database = array_pop($host);
53                         unset($host);
54                 }
55         }
56
57         if($user == 'auto') {
58                 if(isset($GLOBALS['db_username'])) {
59                         $user = $GLOBALS['db_username'];
60                 } else {
61                         $user = 'www';
62                 }
63         }
64
65         if($pass == 'auto') {
66                 if(isset($GLOBALS['db_password'])) {
67                         $pass = $GLOBALS['db_password'];
68                 } else {
69                         $pass = '';
70                 }
71         }
72
73         $GLOBALS['wfpl_db_handle'] = mysql_connect($host, $user, $pass);
74         if(!$GLOBALS['wfpl_db_handle']) {
75                 die('Could not connect to the database: ' . mysql_error());
76         }
77
78         if(!mysql_select_db($database, $GLOBALS['wfpl_db_handle'])) {
79                 die("Couldn not access database \"$database\": " . mysql_error($GLOBALS['wfpl_db_handle']));
80         }
81
82         return $GLOBALS['wfpl_db_handle'];
83 }
84
85 # Unless you're doing something unusual like an ALTER TABLE don't call this directly
86 function db_send_query($sql) {
87         #echo("Sending query: " . enc_html($sql) . "<br>\n");
88         $result = mysql_query($sql, $GLOBALS['wfpl_db_handle']);
89         if(!$result) {
90                 die(enc_html('DATABASE ERROR: ' . mysql_error($GLOBALS['wfpl_db_handle']) . ' in the following query: ' . $sql));
91         }
92
93         return $result;
94 }
95
96 # All select queries use this to generate the where clause, so they can work
97 # like printf. Currently three % codes are supported:
98 #
99 # %%  put a % in the output
100 # %i  put an integer in the output (strips non-numeric digits, and puts in 0 if blank)
101 # %"  output double quotes, surrounding the variable which is encoded to be in there.
102 # %s  output encoded to be in double quotes, but don't output the quotes
103 #
104 # complex example: db_get_rows('mytable', 'id', 'where name=%" or company like "%%%s%%"', $name, $company_partial);
105
106 function db_printf($str) {
107         $args = func_get_args();
108         $args = array_slice($args, 1);
109         return _db_printf($str, $args);
110 }
111
112 # This function does the work, but takes the parameters in an array
113 function _db_printf($str, $args) {
114         $out = '';
115         while($str) {
116                 $pos = strpos($str, '%');
117                 if($pos === false) { # not found
118                         # we hit the end.
119                         return $out . $str;
120                 }
121                 # move everything up to (but not including) % to the output
122                 $out .= substr($str, 0, $pos);
123
124                 # grab the character after the %
125                 $chr = substr($str, $pos + 1, 1);
126
127                 # remove the stuff we've read from input
128                 $str = substr($str, $pos + 2);
129
130                 if($chr == '"') {
131                         $out .= '"' . enc_sql(array_shift($args)) . '"';
132                 } elseif($chr == 's') {
133                         $out .= enc_sql(array_shift($args));
134                 } elseif($chr == 'i') {
135                         $int = format_int(array_shift($args));
136                         if($int == '') $int = '0';
137                         $out .= $int;
138                 } else {
139                         $out .= $chr;
140                 }
141         }
142
143         return $out;
144 }
145
146
147 function db_send_get($table, $columns, $where, $args) {
148         $sql = "SELECT $columns FROM $table";
149         if($where) {
150                 $sql .= ' ' . _db_printf($where, $args);
151         }
152
153         return db_send_query($sql);
154 }
155
156
157 function db_get_rows($table, $columns, $where = '') {
158         $args = func_get_args();
159         $args = array_slice($args, 3);
160         $result = db_send_get($table, $columns, $where, $args);
161
162         $rows = array();
163         while($row = mysql_fetch_row($result)) {
164                 $rows[] = $row;
165         }
166
167         mysql_free_result($result);
168
169         return $rows;
170 }
171
172 function db_get_column($table, $columns, $where = '') {
173         $args = func_get_args();
174         $args = array_slice($args, 3);
175         $result = db_send_get($table, $columns, $where, $args);
176
177         $column = array();
178         while($row = mysql_fetch_row($result)) {
179                 $column[] = $row[0];
180         }
181
182         mysql_free_result($result);
183
184         return $column;
185 }
186
187 function db_get_row($table, $columns, $where = '') {
188         $args = func_get_args();
189         $args = array_slice($args, 3);
190         $result = db_send_get($table, $columns, $where, $args);
191
192         $row = mysql_fetch_row($result);
193
194         mysql_free_result($result);
195
196         return $row;
197 }
198
199 function db_get_value($table, $columns, $where = '') {
200         $args = func_get_args();
201         $args = array_slice($args, 3);
202         $result = db_send_get($table, $columns, $where, $args);
203
204         $value = mysql_fetch_row($result);
205         if($value !== false) {
206                 $value = $value[0];
207         }
208
209         mysql_free_result($result);
210
211         return $value;
212 }
213
214 function db_count($table, $where = '') {
215         $args = func_get_args();
216         array_splice($args, 1, 0, array('count(*)'));
217         return call_user_func_array('db_get_value', $args);
218 }
219
220 # call either of these ways:
221 #
222 # db_insert('people', 'name,company', 'jason', 'widgets ltd');
223 # or
224 # db_insert('people', 'name,company', array('jason', 'widgets ltd'));
225 function db_insert($table, $columns, $values) {
226         if(!is_array($values)) {
227                 $values = func_get_args();
228                 $values = array_slice($values, 2);
229         }
230         
231         db_insert_ish('INSERT', $table, $columns, $values);
232 }
233 # same as above, except uses the "replace" command instead of "insert"
234 function db_replace($table, $columns, $values) {
235         if(!is_array($values)) {
236                 $values = func_get_args();
237                 $values = array_slice($values, 2);
238         }
239         
240         db_insert_ish('REPLACE', $table, $columns, $values);
241 }
242         
243 # return the value mysql made up for the auto_increment field (for the last insert)
244 function db_auto_id() {
245         return mysql_insert_id($GLOBALS['wfpl_db_handle']);
246 }
247
248
249 # used to implement db_insert() and db_replace()
250 function db_insert_ish($command, $table, $columns, $values) {
251
252         $sql = '';
253         foreach($values as $value) {
254                 if($sql) $sql .= ',';
255                 $sql .= '"' . enc_sql($value) . '"';
256         }
257
258         $sql = "$command INTO $table ($columns) values($sql)";
259
260         db_send_query($sql);
261 }
262
263 # to be consistant with the syntax of the other db functions, $values can be an
264 # array, a single value, or multiple parameters.
265 #
266 # as usual the where clause stuff is optional, but it will ofcourse update the
267 # whole table if you leave it off.
268 #
269 # examples:
270 #
271 # # name everybody Bruce
272 # db_update('users', 'name', 'Bruce');
273 #
274 # # name user #6 Bruce
275 # db_update('users', 'name', 'Bruce', 'where id=%i', 6);
276 #
277 # # update the whole bit for user #6
278 # db_update('users', 'name,email,description', 'Bruce', 'bruce@example.com', 'is a cool guy', 'where id=%i', 6);
279 #
280 # # update the whole bit for user #6 (passing data as an array)
281 # $data = array('Bruce', 'bruce@example.com', 'is a cool guy');
282 # db_update('users', 'name,email,description', $data, 'where id=%i', 6);
283
284 # The prototype is really something like this:
285 # db_update(table, columns, values..., where(optional), where_args...(optional))
286 function db_update($table, $columns, $values) {
287         $args = func_get_args();
288         $args = array_slice($args, 2);
289         $columns = explode(',', $columns);
290         $num_fields = count($columns);
291
292         if(is_array($values)) {
293                 $args = array_slice($args, 1);
294         } else {
295                 $values = array_slice($args, 0, $num_fields);
296                 $args = array_slice($args, $num_fields);
297         }
298
299         $sql = '';
300         for($i = 0; $i < $num_fields; ++$i) {
301                 if($sql != '') {
302                         $sql .= ', ';
303                 }
304                 $sql .= $columns[$i] . ' = "' . enc_sql($values[$i]) . '"';
305         }
306
307
308         $sql = "UPDATE $table SET $sql";
309
310         # if there's any more arguments
311         if($args) {
312                 $where = $args[0];
313                 $args = array_slice($args, 1);
314
315                 $sql .= ' ';
316                 # any left for where claus arguments?
317                 if($args) {
318                         $sql .= _db_printf($where, $args);
319                 } else {
320                         $sql .= $where;
321                 }
322
323         }
324
325         db_send_query($sql);
326 }
327
328 # pass args for printf-style where clause as usual
329 function db_delete($table, $where = '') {
330         $sql = "DELETE FROM $table";
331         if($where) {
332                 $sql .= ' ';
333                 $args = func_get_args();
334                 $args = array_slice($args, 2);
335                 if($args) {
336                         $sql .= _db_printf($where, $args);
337                 } else {
338                         $sql .= $where;
339                 }
340         }
341
342         db_send_query($sql);
343 }
344
345 ?>