3 # This program is in the public domain within the United States. Additionally,
4 # we waive copyright and related rights in the work worldwide through the CC0
5 # 1.0 Universal public domain dedication, which can be found at
6 # http://creativecommons.org/publicdomain/zero/1.0/
9 require_once(__DIR__.'/'.'encode.php');
10 require_once(__DIR__.'/'.'format.php');
12 # db_connect() -- connect to a mysql database (automatically, later, when/if needed)
13 # db_connect_now() -- connect to a mysql database immediately
17 # database: the name of the database you want to connect to. Defaults to the
18 # second-to-last part of the domain name. eg for foo.example.com it would be
21 # user: username for connecting to the database. Defaults to
22 # $GLOBALS['db_username'] or (if that's not set) "www".
24 # password: password for connecting to the database. Defaults to
25 # $GLOBALS['db_password'] or (if that's not set "".
29 # the database connection handle. You'll only need this if you want to have
30 # multiple databases open at once.
31 function db_connect() {
32 if (isset($GLOBALS['wfpl_db_handle'])) {
33 mysqli_close($GLOBALS['wfpl_db_handle']);
34 unset($GLOBALS['wfpl_db_handle']);
36 $GLOBALS['wfpl_db_connect_args'] = func_get_args();
38 function db_connect_now($database = 'auto', $user = 'auto', $pass = 'auto', $host = 'localhost', $encoding = 'utf8') {
39 if($database == 'auto') {
40 if(isset($GLOBALS['db_name'])) {
41 $database = $GLOBALS['db_name'];
43 $host = $_SERVER['SERVER_NAME'];
44 $host = explode('.', $host);
46 $database = array_pop($host);
52 if(isset($GLOBALS['db_username'])) {
53 $user = $GLOBALS['db_username'];
60 if(isset($GLOBALS['db_password'])) {
61 $pass = $GLOBALS['db_password'];
67 $GLOBALS['wfpl_db_handle'] = @mysqli_connect($host, $user, $pass);
68 if(!$GLOBALS['wfpl_db_handle']) {
69 die('Server error: Database connection failed');
70 # to show username and host: mysqli_connect_error()
73 mysqli_set_charset($GLOBALS['wfpl_db_handle'], $encoding);
75 if(!mysqli_select_db($GLOBALS['wfpl_db_handle'], $database)) {
76 die("Couldn not access database \"$database\": " . mysqli_error($GLOBALS['wfpl_db_handle']));
79 return $GLOBALS['wfpl_db_handle'];
81 # for internal use (helps implement the auto-connect feature of db_connect())
82 function _db_connection_needed() {
83 if (isset($GLOBALS['wfpl_db_handle'])) {
86 if (isset($GLOBALS['wfpl_db_connect_args'])) {
87 return call_user_func_array('db_connect_now', $GLOBALS['wfpl_db_connect_args']);
89 die('Error: you must call db_connect() or db_auto_connect() first!');
92 function db_enc_sql($str) {
93 _db_connection_needed();
94 return mysqli_real_escape_string(isset($GLOBALS['wfpl_db_handle']) ? $GLOBALS['wfpl_db_handle'] : null, $str);
97 # Unless you're doing something unusual like an ALTER TABLE don't call this directly
98 function db_send_query($sql) {
99 _db_connection_needed();
100 #echo("Sending query: " . enc_html($sql) . "<br>\n");
101 $result = mysqli_query($GLOBALS['wfpl_db_handle'], $sql);
103 die(enc_html('DATABASE ERROR: ' . mysqli_error($GLOBALS['wfpl_db_handle']) . ' in the following query: ' . $sql));
109 # All select queries use this to generate the where clause, so they can work
110 # like printf. Currently three % codes are supported:
112 # %% put a % in the output
113 # %i put an integer in the output (strips non-numeric digits, and puts in 0 if blank)
114 # %f put a floating point value in the output (strips non-numeric digits, puts in 0.0 if not valid)
115 # %" output double quotes, surrounding the variable which is encoded to be in there.
116 # %s output encoded to be in double quotes, but don't output the quotes
117 # %$ output argument as-is, no encoding. Make sure you quote everything from the user!
119 # complex example: db_get_rows('mytable', 'id', 'where name=%" or company like "%%%s%%"', $name, $company_partial);
121 function db_printf($str) {
122 $args = func_get_args();
123 $args = array_slice($args, 1);
124 return _db_printf($str, $args);
127 # This function does the work, but takes the parameters in an array
128 function _db_printf($str, $args) {
131 $pos = strpos($str, '%');
132 if($pos === false) { # not found
136 # move everything up to (but not including) % to the output
137 $out .= substr($str, 0, $pos);
139 # grab the character after the %
140 $chr = substr($str, $pos + 1, 1);
142 # remove the stuff we've read from input
143 $str = substr($str, $pos + 2);
146 $out .= '"' . db_enc_sql(array_shift($args)) . '"';
147 } elseif($chr == 's') {
148 $out .= db_enc_sql(array_shift($args));
149 } elseif($chr == 'i') {
150 $int = format_int(array_shift($args));
151 if($int == '') $int = '0';
153 } elseif($chr == 'f') {
154 $arg = array_shift($args);
155 if(is_numeric($arg)) {
156 $arg = sprintf("%f", $arg);
158 $arg = format_decimal($arg);
159 if(strlen($arg) < 1) {
163 } elseif($chr == '$') {
164 $out .= array_shift($args);
175 function db_send_get($table, $columns, $where, $args) {
176 $sql = "SELECT $columns FROM $table";
178 $sql .= ' ' . _db_printf($where, $args);
181 return db_send_query($sql);
185 # if no results: returs []
186 function db_get_rows($table, $columns, $where = '') {
187 $args = func_get_args();
188 $args = array_slice($args, 3);
189 $result = db_send_get($table, $columns, $where, $args);
192 while($row = mysqli_fetch_row($result)) {
196 mysqli_free_result($result);
201 # like db_get_rows, but return array of hashes.
202 # if no results: returs []
203 function db_get_assocs($table, $columns, $where = '') {
204 $args = func_get_args();
205 $args = array_slice($args, 3);
206 $result = db_send_get($table, $columns, $where, $args);
209 while($row = mysqli_fetch_assoc($result)) {
213 mysqli_free_result($result);
218 # if no results: returs []
219 function db_get_column($table, $columns, $where = '') {
220 $args = func_get_args();
221 $args = array_slice($args, 3);
222 $result = db_send_get($table, $columns, $where, $args);
225 while($row = mysqli_fetch_row($result)) {
229 mysqli_free_result($result);
234 # returns first matching row
235 # if no results: returns false
236 function db_get_row($table, $columns, $where = '') {
237 $args = func_get_args();
238 $args = array_slice($args, 3);
239 $result = db_send_get($table, $columns, $where, $args);
241 $row = mysqli_fetch_row($result);
243 mysqli_free_result($result);
248 # like db_get_row, but return a hash.
249 # if no results: returns false
250 function db_get_assoc($table, $columns, $where = '') {
251 $args = func_get_args();
252 $args = array_slice($args, 3);
253 $result = db_send_get($table, $columns, $where, $args);
255 $row = mysqli_fetch_assoc($result);
257 mysqli_free_result($result);
262 # if no results: returns false
263 function db_get_value($table, $column, $where = '') {
264 $args = func_get_args();
265 $args = array_slice($args, 3);
266 $result = db_send_get($table, $column, $where, $args);
268 $value = mysqli_fetch_row($result);
269 if($value !== false) {
273 mysqli_free_result($result);
279 function db_count($table, $where = '') {
280 $args = func_get_args();
281 array_splice($args, 1, 0, array('count(*)'));
282 return (int) call_user_func_array('db_get_value', $args);
285 # call either of these ways:
287 # db_insert('people', 'name,company', 'jason', 'widgets ltd');
289 # db_insert('people', 'name,company', array('jason', 'widgets ltd'));
290 function db_insert($table, $columns, $values) {
291 if(!is_array($values)) {
292 $values = func_get_args();
293 $values = array_slice($values, 2);
296 db_insert_ish('INSERT', $table, $columns, $values);
299 # like db_insert() above, but instead of passing columns and data separately,
300 # you can pass one array with the column names as keys and the data as values
301 function db_insert_assoc($table, $data) {
302 $args = func_get_args();
303 $args = array_slice($args, 2);
306 foreach($data as $key => $value) {
310 array_unshift($args, $table, join(',', $columns), $values);
311 call_user_func_array('db_insert', $args);
314 # same as above, except uses the "replace" command instead of "insert"
315 function db_replace($table, $columns, $values) {
316 if(!is_array($values)) {
317 $values = func_get_args();
318 $values = array_slice($values, 2);
321 db_insert_ish('REPLACE', $table, $columns, $values);
324 # return the value mysql made up for the auto_increment field (for the last insert)
325 function db_auto_id() {
326 _db_connection_needed();
327 return mysqli_insert_id($GLOBALS['wfpl_db_handle']);
331 # used to implement db_insert() and db_replace()
332 function db_insert_ish($command, $table, $columns, $values) {
335 foreach($values as $value) {
336 if($sql) $sql .= ',';
337 $sql .= '"' . db_enc_sql($value) . '"';
340 $sql = "$command INTO $table ($columns) values($sql)";
345 # to be consistent with the syntax of the other db functions, $values can be an
346 # array, a single value, or multiple parameters.
348 # as usual the where clause stuff is optional, but it will of course update the
349 # whole table if you leave it off.
353 # # name everybody Bruce
354 # db_update('users', 'name', 'Bruce');
356 # # name user #6 Bruce
357 # db_update('users', 'name', 'Bruce', 'where id=%i', 6);
359 # # update the whole bit for user #6
360 # db_update('users', 'name,email,description', 'Bruce', 'bruce@example.com', 'is a cool guy', 'where id=%i', 6);
362 # # update the whole bit for user #6 (passing data as an array)
363 # $data = array('Bruce', 'bruce@example.com', 'is a cool guy');
364 # db_update('users', 'name,email,description', $data, 'where id=%i', 6);
366 # The prototype is really something like this:
367 # db_update(table, columns, values..., where(optional), where_args...(optional))
368 function db_update($table, $columns, $values) {
369 $args = func_get_args();
370 $args = array_slice($args, 2);
371 $columns = explode(',', $columns);
372 $num_fields = count($columns);
374 if(is_array($values)) {
375 $values = array_values($values);
376 $args = array_slice($args, 1);
378 $values = array_slice($args, 0, $num_fields);
379 $args = array_slice($args, $num_fields);
383 for($i = 0; $i < $num_fields; ++$i) {
387 $sql .= $columns[$i] . ' = "' . db_enc_sql($values[$i]) . '"';
391 $sql = "UPDATE $table SET $sql";
393 # if there's any more arguments
396 $args = array_slice($args, 1);
399 # any left for printf arguments?
401 $sql .= _db_printf($where, $args);
411 # like db_update() above, but instead of passing columns and data separately,
412 # you can pass one array with the column names as keys and the data as values
413 function db_update_assoc($table, $data) {
414 $args = func_get_args();
415 $args = array_slice($args, 2);
418 foreach($data as $key => $value) {
422 array_unshift($args, $values);
423 array_unshift($args, join(',', $columns));
424 array_unshift($args, $table);
425 call_user_func_array('db_update', $args);
428 # pass args for printf-style where clause as usual
429 function db_delete($table, $where = '') {
430 $sql = "DELETE FROM $table";
433 $args = func_get_args();
434 $args = array_slice($args, 2);
436 $sql .= _db_printf($where, $args);
446 define('DB_ORD_MAX', 2000000000);
448 function db_reposition_respace($table, $field, $where = '') {
450 $andand = " && ($where) ";
452 $ids = db_get_column($table, 'id', "where $field != 0 $andand order by $field");
455 # should never happen
458 $inc = floor(DB_ORD_MAX / ($c + 1));
460 foreach($ids as $id) {
461 db_update($table, $field, $cur, 'where id=%i', $id);
466 # this function facilitates letting the user manually sort records (with (int) $field != 0)
468 # When editing a particular row, give the user a pulldown, with 0 -> first, 1 -> second, etc, and pass this integer to db_reposition (3rd parameter). The value "ignored" can be passed, and the row will be given a sort value of 0 and ignored for all sorting.
470 # $pretty is used in error messages to refer to the row, it defaults to whatever you pass for $table.
472 # return value is the "ord" value you should set/insert into your database
474 function db_reposition($table, $row_id, $new_pos, $field = 'ord', $pretty = 'same as $table', $where = '', $renumbered_already = false) {
475 if($pretty == 'same as $table') {
479 $andand = " && ($where) ";
482 if($new_pos === 'ignored') {
487 # strategy: calculate $prev_ord and $next_ord. If there's no space between, renumber and recurse
488 if($new_pos == '0') {
489 $row = db_get_row($table, "id,$field", "where $field != 0 $andand order by $field limit 1");
491 list($first_row_id, $first_row_ord) = $row;
492 if($first_row_id == $row_id) {
494 return $first_row_ord;
496 $next_ord = $first_row_ord;
498 # this is the only row, put it in the middle
499 return '' + floor(DB_ORD_MAX / 2);
504 $new_pos = format_int_0($new_pos);
505 $rows = db_get_rows($table, "id,$field", "where $field != 0 $andand order by $field limit %i,2", $new_pos - 1);
507 message("Sorry, couldn't find the $pretty you asked to put this $pretty after. Putting it first instead.");
508 return db_reposition($table, $row_id, '0', $field, $pretty, $where);
510 list($prev_id, $prev_ord) = $rows[0];
511 if($prev_id == $row_id) {
512 # after self? this shouldn't happen
515 if(count($rows) == 1) {
517 $next_ord = DB_ORD_MAX;
519 list($next_id, $next_ord) = $rows[1];
520 if($next_id == $row_id) {
521 # after prev (already there)
527 if($prev_ord + 1 == $next_ord || $prev_ord == $next_ord) { # the latter should never happen
528 if($renumbered_already) {
529 message("Programmer error in $pretty ordering code. Please tell your website administrator.");
530 return '' . rand(2, DB_ORD_MAX - 2); # reasonably unlikely to be the same as some other ord
532 db_reposition_respace($table, $field, $where);
533 return db_reposition($table, $row_id, $new_pos, $field, $pretty, $where, $renumbered_already = true);
535 return $prev_ord + round(($next_ord - $prev_ord) / 2);