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