2 use \Friendica\Core\System;
3 use Friendica\Database\DBM;
5 require_once('include/datetime.php');
8 * @class MySQL database class
10 * This class is for the low level database stuff that does driver specific things.
14 public static $connected = true;
16 private static $_server_info = '';
18 private static $driver;
19 private static $error = false;
20 private static $errorno = 0;
21 private static $affected_rows = 0;
22 private static $in_transaction = false;
23 private static $relation = array();
25 public static function connect($serveraddr, $user, $pass, $db, $install = false) {
26 if (!is_null(self::$db)) {
32 $stamp1 = microtime(true);
34 $serveraddr = trim($serveraddr);
36 $serverdata = explode(':', $serveraddr);
37 $server = $serverdata[0];
39 if (count($serverdata) > 1) {
40 $port = trim($serverdata[1]);
43 $server = trim($server);
48 if (!(strlen($server) && strlen($user))) {
49 self::$connected = false;
55 if (strlen($server) && ($server !== 'localhost') && ($server !== '127.0.0.1')) {
56 if (! dns_get_record($server, DNS_A + DNS_CNAME + DNS_PTR)) {
57 self::$error = sprintf(t('Cannot locate DNS info for database server \'%s\''), $server);
58 self::$connected = false;
65 if (class_exists('\PDO') && in_array('mysql', PDO::getAvailableDrivers())) {
66 self::$driver = 'pdo';
67 $connect = "mysql:host=".$server.";dbname=".$db;
70 $connect .= ";port=".$port;
73 if (isset($a->config["system"]["db_charset"])) {
74 $connect .= ";charset=".$a->config["system"]["db_charset"];
77 self::$db = @new PDO($connect, $user, $pass);
78 self::$connected = true;
79 } catch (PDOException $e) {
80 self::$connected = false;
84 if (!self::$connected && class_exists('mysqli')) {
85 self::$driver = 'mysqli';
86 self::$db = @new mysqli($server, $user, $pass, $db, $port);
87 if (!mysqli_connect_errno()) {
88 self::$connected = true;
90 if (isset($a->config["system"]["db_charset"])) {
91 self::$db->set_charset($a->config["system"]["db_charset"]);
96 if (!self::$connected && function_exists('mysql_connect')) {
97 self::$driver = 'mysql';
98 self::$db = mysql_connect($serveraddr, $user, $pass);
99 if (self::$db && mysql_select_db($db, self::$db)) {
100 self::$connected = true;
102 if (isset($a->config["system"]["db_charset"])) {
103 mysql_set_charset($a->config["system"]["db_charset"], self::$db);
108 // No suitable SQL driver was found.
109 if (!self::$connected) {
112 system_unavailable();
115 $a->save_timestamp($stamp1, "network");
121 * @brief Returns the MySQL server version string
123 * This function discriminate between the deprecated mysql API and the current
124 * object-oriented mysqli API. Example of returned string: 5.5.46-0+deb8u1
128 public static function server_info() {
129 if (self::$_server_info == '') {
130 switch (self::$driver) {
132 self::$_server_info = self::$db->getAttribute(PDO::ATTR_SERVER_VERSION);
135 self::$_server_info = self::$db->server_info;
138 self::$_server_info = mysql_get_server_info(self::$db);
142 return self::$_server_info;
146 * @brief Returns the selected database name
150 public static function database_name() {
151 $ret = self::p("SELECT DATABASE() AS `db`");
152 $data = self::inArray($ret);
153 return $data[0]['db'];
157 * @brief Analyze a database query and log this if some conditions are met.
159 * @param string $query The database query that will be analyzed
161 private static function log_index($query) {
164 if (empty($a->config["system"]["db_log_index"])) {
168 // Don't explain an explain statement
169 if (strtolower(substr($query, 0, 7)) == "explain") {
173 // Only do the explain on "select", "update" and "delete"
174 if (!in_array(strtolower(substr($query, 0, 6)), array("select", "update", "delete"))) {
178 $r = self::p("EXPLAIN ".$query);
179 if (!DBM::is_result($r)) {
183 $watchlist = explode(',', $a->config["system"]["db_log_index_watch"]);
184 $blacklist = explode(',', $a->config["system"]["db_log_index_blacklist"]);
186 while ($row = dba::fetch($r)) {
187 if ((intval($a->config["system"]["db_loglimit_index"]) > 0)) {
188 $log = (in_array($row['key'], $watchlist) &&
189 ($row['rows'] >= intval($a->config["system"]["db_loglimit_index"])));
194 if ((intval($a->config["system"]["db_loglimit_index_high"]) > 0) && ($row['rows'] >= intval($a->config["system"]["db_loglimit_index_high"]))) {
198 if (in_array($row['key'], $blacklist) || ($row['key'] == "")) {
203 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
204 @file_put_contents($a->config["system"]["db_log_index"], datetime_convert()."\t".
205 $row['key']."\t".$row['rows']."\t".$row['Extra']."\t".
206 basename($backtrace[1]["file"])."\t".
207 $backtrace[1]["line"]."\t".$backtrace[2]["function"]."\t".
208 substr($query, 0, 2000)."\n", FILE_APPEND);
213 public static function escape($str) {
214 switch (self::$driver) {
216 return substr(@self::$db->quote($str, PDO::PARAM_STR), 1, -1);
218 return @self::$db->real_escape_string($str);
220 return @mysql_real_escape_string($str,self::$db);
224 public static function connected() {
227 switch (self::$driver) {
229 $r = dba::p("SELECT 1");
230 if (DBM::is_result($r)) {
231 $row = dba::inArray($r);
232 $connected = ($row[0]['1'] == '1');
236 $connected = self::$db->ping();
239 $connected = mysql_ping(self::$db);
246 * @brief Replaces ANY_VALUE() function by MIN() function,
247 * if the database server does not support ANY_VALUE().
249 * Considerations for Standard SQL, or MySQL with ONLY_FULL_GROUP_BY (default since 5.7.5).
250 * ANY_VALUE() is available from MySQL 5.7.5 https://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html
251 * A standard fall-back is to use MIN().
253 * @param string $sql An SQL string without the values
254 * @return string The input SQL string modified if necessary.
256 public static function any_value_fallback($sql) {
257 $server_info = self::server_info();
258 if (version_compare($server_info, '5.7.5', '<') ||
259 (stripos($server_info, 'MariaDB') !== false)) {
260 $sql = str_ireplace('ANY_VALUE(', 'MIN(', $sql);
266 * @brief beautifies the query - useful for "SHOW PROCESSLIST"
268 * This is safe when we bind the parameters later.
269 * The parameter values aren't part of the SQL.
271 * @param string $sql An SQL string without the values
272 * @return string The input SQL string modified if necessary.
274 public static function clean_query($sql) {
275 $search = array("\t", "\n", "\r", " ");
276 $replace = array(' ', ' ', ' ', ' ');
279 $sql = str_replace($search, $replace, $sql);
280 } while ($oldsql != $sql);
287 * @brief Replaces the ? placeholders with the parameters in the $args array
289 * @param string $sql SQL query
290 * @param array $args The parameters that are to replace the ? placeholders
291 * @return string The replaced SQL query
293 private static function replace_parameters($sql, $args) {
295 foreach ($args AS $param => $value) {
296 if (is_int($args[$param]) || is_float($args[$param])) {
297 $replace = intval($args[$param]);
299 $replace = "'".self::escape($args[$param])."'";
302 $pos = strpos($sql, '?', $offset);
303 if ($pos !== false) {
304 $sql = substr_replace($sql, $replace, $pos, 1);
306 $offset = $pos + strlen($replace);
312 * @brief Convert parameter array to an universal form
313 * @param array $args Parameter array
314 * @return array universalized parameter array
316 private static function getParam($args) {
319 // When the second function parameter is an array then use this as the parameter array
320 if ((count($args) > 0) && (is_array($args[1]))) {
328 * @brief Executes a prepared statement that returns data
329 * @usage Example: $r = p("SELECT * FROM `item` WHERE `guid` = ?", $guid);
331 * Please only use it with complicated queries.
332 * For all regular queries please use dba::select or dba::exists
334 * @param string $sql SQL statement
335 * @return object statement object
337 public static function p($sql) {
340 $stamp1 = microtime(true);
342 $params = self::getParam(func_get_args());
344 // Renumber the array keys to be sure that they fit
347 foreach ($params AS $param) {
348 // Avoid problems with some MySQL servers and boolean values. See issue #3645
349 if (is_bool($param)) {
350 $param = (int)$param;
352 $args[++$i] = $param;
355 if (!self::$connected) {
359 if ((substr_count($sql, '?') != count($args)) && (count($args) > 0)) {
360 // Question: Should we continue or stop the query here?
361 logger('Parameter mismatch. Query "'.$sql.'" - Parameters '.print_r($args, true), LOGGER_DEBUG);
364 $sql = self::clean_query($sql);
365 $sql = self::any_value_fallback($sql);
369 if (x($a->config,'system') && x($a->config['system'], 'db_callstack')) {
370 $sql = "/*".System::callstack()." */ ".$sql;
375 self::$affected_rows = 0;
377 // We have to make some things different if this function is called from "e"
378 $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2);
380 if (isset($trace[1])) {
381 $called_from = $trace[1];
383 // We use just something that is defined to avoid warnings
384 $called_from = $trace[0];
386 // We are having an own error logging in the function "e"
387 $called_from_e = ($called_from['function'] == 'e');
389 switch (self::$driver) {
391 // If there are no arguments we use "query"
392 if (count($args) == 0) {
393 if (!$retval = self::$db->query($sql)) {
394 $errorInfo = self::$db->errorInfo();
395 self::$error = $errorInfo[2];
396 self::$errorno = $errorInfo[1];
400 self::$affected_rows = $retval->rowCount();
404 if (!$stmt = self::$db->prepare($sql)) {
405 $errorInfo = self::$db->errorInfo();
406 self::$error = $errorInfo[2];
407 self::$errorno = $errorInfo[1];
412 foreach ($args AS $param => $value) {
413 $stmt->bindParam($param, $args[$param]);
416 if (!$stmt->execute()) {
417 $errorInfo = $stmt->errorInfo();
418 self::$error = $errorInfo[2];
419 self::$errorno = $errorInfo[1];
423 self::$affected_rows = $retval->rowCount();
427 // There are SQL statements that cannot be executed with a prepared statement
428 $parts = explode(' ', $orig_sql);
429 $command = strtolower($parts[0]);
430 $can_be_prepared = in_array($command, array('select', 'update', 'insert', 'delete'));
432 // The fallback routine is called as well when there are no arguments
433 if (!$can_be_prepared || (count($args) == 0)) {
434 $retval = self::$db->query(self::replace_parameters($sql, $args));
435 if (self::$db->errno) {
436 self::$error = self::$db->error;
437 self::$errorno = self::$db->errno;
440 if (isset($retval->num_rows)) {
441 self::$affected_rows = $retval->num_rows;
443 self::$affected_rows = self::$db->affected_rows;
449 $stmt = self::$db->stmt_init();
451 if (!$stmt->prepare($sql)) {
452 self::$error = $stmt->error;
453 self::$errorno = $stmt->errno;
460 foreach ($args AS $param => $value) {
461 if (is_int($args[$param])) {
463 } elseif (is_float($args[$param])) {
465 } elseif (is_string($args[$param])) {
470 $values[] = &$args[$param];
473 if (count($values) > 0) {
474 array_unshift($values, $params);
475 call_user_func_array(array($stmt, 'bind_param'), $values);
478 if (!$stmt->execute()) {
479 self::$error = self::$db->error;
480 self::$errorno = self::$db->errno;
483 $stmt->store_result();
485 self::$affected_rows = $retval->affected_rows;
489 // For the old "mysql" functions we cannot use prepared statements
490 $retval = mysql_query(self::replace_parameters($sql, $args), self::$db);
491 if (mysql_errno(self::$db)) {
492 self::$error = mysql_error(self::$db);
493 self::$errorno = mysql_errno(self::$db);
495 self::$affected_rows = mysql_affected_rows($retval);
497 // Due to missing mysql_* support this here wasn't tested at all
498 // See here: http://php.net/manual/en/function.mysql-num-rows.php
499 if (self::$affected_rows <= 0) {
500 self::$affected_rows = mysql_num_rows($retval);
506 // We are having an own error logging in the function "e"
507 if ((self::$errorno != 0) && !$called_from_e) {
508 // We have to preserve the error code, somewhere in the logging it get lost
509 $error = self::$error;
510 $errorno = self::$errorno;
512 logger('DB Error '.self::$errorno.': '.self::$error."\n".
513 System::callstack(8)."\n".self::replace_parameters($sql, $params));
515 self::$error = $error;
516 self::$errorno = $errorno;
519 $a->save_timestamp($stamp1, 'database');
521 if (x($a->config,'system') && x($a->config['system'], 'db_log')) {
523 $stamp2 = microtime(true);
524 $duration = (float)($stamp2 - $stamp1);
526 if (($duration > $a->config["system"]["db_loglimit"])) {
527 $duration = round($duration, 3);
528 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
530 @file_put_contents($a->config["system"]["db_log"], datetime_convert()."\t".$duration."\t".
531 basename($backtrace[1]["file"])."\t".
532 $backtrace[1]["line"]."\t".$backtrace[2]["function"]."\t".
533 substr(self::replace_parameters($sql, $args), 0, 2000)."\n", FILE_APPEND);
540 * @brief Executes a prepared statement like UPDATE or INSERT that doesn't return data
542 * Please use dba::delete, dba::insert, dba::update, ... instead
544 * @param string $sql SQL statement
545 * @return boolean Was the query successfull? False is returned only if an error occurred
547 public static function e($sql) {
550 $stamp = microtime(true);
552 $params = self::getParam(func_get_args());
554 // In a case of a deadlock we are repeating the query 20 times
558 $stmt = self::p($sql, $params);
560 if (is_bool($stmt)) {
562 } elseif (is_object($stmt)) {
570 } while ((self::$errorno == 1213) && (--$timeout > 0));
572 if (self::$errorno != 0) {
573 // We have to preserve the error code, somewhere in the logging it get lost
574 $error = self::$error;
575 $errorno = self::$errorno;
577 logger('DB Error '.self::$errorno.': '.self::$error."\n".
578 System::callstack(8)."\n".self::replace_parameters($sql, $params));
580 self::$error = $error;
581 self::$errorno = $errorno;
584 $a->save_timestamp($stamp, "database_write");
590 * @brief Check if data exists
592 * @param string $table Table name
593 * @param array $condition array of fields for condition
595 * @return boolean Are there rows for that condition?
597 public static function exists($table, $condition) {
604 $array_element = each($condition);
605 $array_key = $array_element['key'];
606 if (!is_int($array_key)) {
607 $fields = array($array_key);
610 $stmt = self::select($table, $fields, $condition, array('limit' => 1, 'only_query' => true));
612 if (is_bool($stmt)) {
615 $retval = (self::num_rows($stmt) > 0);
624 * @brief Fetches the first row
626 * Please use dba::select or dba::exists whenever this is possible.
628 * @param string $sql SQL statement
629 * @return array first row of query
631 public static function fetch_first($sql) {
632 $params = self::getParam(func_get_args());
634 $stmt = self::p($sql, $params);
636 if (is_bool($stmt)) {
639 $retval = self::fetch($stmt);
648 * @brief Returns the number of affected rows of the last statement
650 * @return int Number of rows
652 public static function affected_rows() {
653 return self::$affected_rows;
657 * @brief Returns the number of columns of a statement
659 * @param object Statement object
660 * @return int Number of columns
662 public static function columnCount($stmt) {
663 if (!is_object($stmt)) {
666 switch (self::$driver) {
668 return $stmt->columnCount();
670 return $stmt->field_count;
672 return mysql_affected_rows($stmt);
677 * @brief Returns the number of rows of a statement
679 * @param object Statement object
680 * @return int Number of rows
682 public static function num_rows($stmt) {
683 if (!is_object($stmt)) {
686 switch (self::$driver) {
688 return $stmt->rowCount();
690 return $stmt->num_rows;
692 return mysql_num_rows($stmt);
698 * @brief Fetch a single row
700 * @param object $stmt statement object
701 * @return array current row
703 public static function fetch($stmt) {
704 if (!is_object($stmt)) {
708 switch (self::$driver) {
710 return $stmt->fetch(PDO::FETCH_ASSOC);
712 if (get_class($stmt) == 'mysqli_result') {
713 return $stmt->fetch_assoc();
716 // This code works, but is slow
718 // Bind the result to a result array
722 for ($x = 0; $x < $stmt->field_count; $x++) {
723 $cols[] = &$cols_num[$x];
726 call_user_func_array(array($stmt, 'bind_result'), $cols);
728 if (!$stmt->fetch()) {
733 // We need to get the field names for the array keys
734 // It seems that there is no better way to do this.
735 $result = $stmt->result_metadata();
736 $fields = $result->fetch_fields();
739 foreach ($cols_num AS $param => $col) {
740 $columns[$fields[$param]->name] = $col;
744 return mysql_fetch_array($stmt, MYSQL_ASSOC);
749 * @brief Insert a row into a table
751 * @param string $table Table name
752 * @param array $param parameter array
753 * @param bool $on_duplicate_update Do an update on a duplicate entry
755 * @return boolean was the insert successfull?
757 public static function insert($table, $param, $on_duplicate_update = false) {
758 $sql = "INSERT INTO `".self::escape($table)."` (`".implode("`, `", array_keys($param))."`) VALUES (".
759 substr(str_repeat("?, ", count($param)), 0, -2).")";
761 if ($on_duplicate_update) {
762 $sql .= " ON DUPLICATE KEY UPDATE `".implode("` = ?, `", array_keys($param))."` = ?";
764 $values = array_values($param);
765 $param = array_merge_recursive($values, $values);
768 return self::e($sql, $param);
772 * @brief Fetch the id of the last insert command
774 * @return integer Last inserted id
776 public static function lastInsertId() {
777 switch (self::$driver) {
779 $id = self::$db->lastInsertId();
782 $id = self::$db->insert_id;
785 $id = mysql_insert_id(self::$db);
792 * @brief Locks a table for exclusive write access
794 * This function can be extended in the future to accept a table array as well.
796 * @param string $table Table name
798 * @return boolean was the lock successful?
800 public static function lock($table) {
801 // See here: https://dev.mysql.com/doc/refman/5.7/en/lock-tables-and-transactions.html
802 self::e("SET autocommit=0");
803 $success = self::e("LOCK TABLES `".self::escape($table)."` WRITE");
805 self::e("SET autocommit=1");
807 self::$in_transaction = true;
813 * @brief Unlocks all locked tables
815 * @return boolean was the unlock successful?
817 public static function unlock() {
818 // See here: https://dev.mysql.com/doc/refman/5.7/en/lock-tables-and-transactions.html
820 $success = self::e("UNLOCK TABLES");
821 self::e("SET autocommit=1");
822 self::$in_transaction = false;
827 * @brief Starts a transaction
829 * @return boolean Was the command executed successfully?
831 public static function transaction() {
832 if (!self::e('COMMIT')) {
835 if (!self::e('START TRANSACTION')) {
838 self::$in_transaction = true;
843 * @brief Does a commit
845 * @return boolean Was the command executed successfully?
847 public static function commit() {
848 if (!self::e('COMMIT')) {
851 self::$in_transaction = false;
856 * @brief Does a rollback
858 * @return boolean Was the command executed successfully?
860 public static function rollback() {
861 if (!self::e('ROLLBACK')) {
864 self::$in_transaction = false;
869 * @brief Build the array with the table relations
871 * The array is build from the database definitions in dbstructure.php
873 * This process must only be started once, since the value is cached.
875 private static function build_relation_data() {
876 $definition = db_definition();
878 foreach ($definition AS $table => $structure) {
879 foreach ($structure['fields'] AS $field => $field_struct) {
880 if (isset($field_struct['relation'])) {
881 foreach ($field_struct['relation'] AS $rel_table => $rel_field) {
882 self::$relation[$rel_table][$rel_field][$table][] = $field;
890 * @brief Delete a row from a table
892 * @param string $table Table name
893 * @param array $param parameter array
894 * @param boolean $in_process Internal use: Only do a commit after the last delete
895 * @param array $callstack Internal use: prevent endless loops
897 * @return boolean|array was the delete successfull? When $in_process is set: deletion data
899 public static function delete($table, $param, $in_process = false, &$callstack = array()) {
902 // Create a key for the loop prevention
903 $key = $table.':'.implode(':', array_keys($param)).':'.implode(':', $param);
905 // We quit when this key already exists in the callstack.
906 if (isset($callstack[$key])) {
910 $callstack[$key] = true;
912 $table = self::escape($table);
914 $commands[$key] = array('table' => $table, 'param' => $param);
916 // To speed up the whole process we cache the table relations
917 if (count(self::$relation) == 0) {
918 self::build_relation_data();
921 // Is there a relation entry for the table?
922 if (isset(self::$relation[$table])) {
923 // We only allow a simple "one field" relation.
924 $field = array_keys(self::$relation[$table])[0];
925 $rel_def = array_values(self::$relation[$table])[0];
927 // Create a key for preventing double queries
928 $qkey = $field.'-'.$table.':'.implode(':', array_keys($param)).':'.implode(':', $param);
930 // When the search field is the relation field, we don't need to fetch the rows
931 // This is useful when the leading record is already deleted in the frontend but the rest is done in the backend
932 if ((count($param) == 1) && ($field == array_keys($param)[0])) {
933 foreach ($rel_def AS $rel_table => $rel_fields) {
934 foreach ($rel_fields AS $rel_field) {
935 $retval = self::delete($rel_table, array($rel_field => array_values($param)[0]), true, $callstack);
936 $commands = array_merge($commands, $retval);
939 // We quit when this key already exists in the callstack.
940 } elseif (!isset($callstack[$qkey])) {
942 $callstack[$qkey] = true;
944 // Fetch all rows that are to be deleted
945 $data = self::select($table, array($field), $param);
947 while ($row = self::fetch($data)) {
948 // Now we accumulate the delete commands
949 $retval = self::delete($table, array($field => $row[$field]), true, $callstack);
950 $commands = array_merge($commands, $retval);
955 // Since we had split the delete command we don't need the original command anymore
956 unset($commands[$key]);
961 // Now we finalize the process
962 $do_transaction = !self::$in_transaction;
964 if ($do_transaction) {
968 $compacted = array();
971 foreach ($commands AS $command) {
972 $condition = $command['param'];
973 $array_element = each($condition);
974 $array_key = $array_element['key'];
975 if (is_int($array_key)) {
976 $condition_string = " WHERE ".array_shift($condition);
978 $condition_string = " WHERE `".implode("` = ? AND `", array_keys($condition))."` = ?";
981 if ((count($command['param']) > 1) || is_int($array_key)) {
982 $sql = "DELETE FROM `".$command['table']."`".$condition_string;
983 logger(self::replace_parameters($sql, $condition), LOGGER_DATA);
985 if (!self::e($sql, $condition)) {
986 if ($do_transaction) {
992 $key_table = $command['table'];
993 $key_param = array_keys($command['param'])[0];
994 $value = array_values($command['param'])[0];
996 // Split the SQL queries in chunks of 100 values
997 // We do the $i stuff here to make the code better readable
998 $i = $counter[$key_table][$key_param];
999 if (count($compacted[$key_table][$key_param][$i]) > 100) {
1003 $compacted[$key_table][$key_param][$i][$value] = $value;
1004 $counter[$key_table][$key_param] = $i;
1007 foreach ($compacted AS $table => $values) {
1008 foreach ($values AS $field => $field_value_list) {
1009 foreach ($field_value_list AS $field_values) {
1010 $sql = "DELETE FROM `".$table."` WHERE `".$field."` IN (".
1011 substr(str_repeat("?, ", count($field_values)), 0, -2).");";
1013 logger(self::replace_parameters($sql, $field_values), LOGGER_DATA);
1015 if (!self::e($sql, $field_values)) {
1016 if ($do_transaction) {
1024 if ($do_transaction) {
1034 * @brief Updates rows
1036 * Updates rows in the database. When $old_fields is set to an array,
1037 * the system will only do an update if the fields in that array changed.
1040 * Only the values in $old_fields are compared.
1041 * This is an intentional behaviour.
1044 * We include the timestamp field in $fields but not in $old_fields.
1045 * Then the row will only get the new timestamp when the other fields had changed.
1047 * When $old_fields is set to a boolean value the system will do this compare itself.
1048 * When $old_fields is set to "true" the system will do an insert if the row doesn't exists.
1051 * Only set $old_fields to a boolean value when you are sure that you will update a single row.
1052 * When you set $old_fields to "true" then $fields must contain all relevant fields!
1054 * @param string $table Table name
1055 * @param array $fields contains the fields that are updated
1056 * @param array $condition condition array with the key values
1057 * @param array|boolean $old_fields array with the old field values that are about to be replaced (true = update on duplicate)
1059 * @return boolean was the update successfull?
1061 public static function update($table, $fields, $condition, $old_fields = array()) {
1062 $table = self::escape($table);
1064 if (count($condition) > 0) {
1065 $array_element = each($condition);
1066 $array_key = $array_element['key'];
1067 if (is_int($array_key)) {
1068 $condition_string = " WHERE ".array_shift($condition);
1070 $condition_string = " WHERE `".implode("` = ? AND `", array_keys($condition))."` = ?";
1073 $condition_string = "";
1076 if (is_bool($old_fields)) {
1077 $do_insert = $old_fields;
1079 $old_fields = self::select($table, array(), $condition, array('limit' => 1));
1081 if (is_bool($old_fields)) {
1083 $values = array_merge($condition, $fields);
1084 return self::insert($table, $values, $do_insert);
1086 $old_fields = array();
1090 $do_update = (count($old_fields) == 0);
1092 foreach ($old_fields AS $fieldname => $content) {
1093 if (isset($fields[$fieldname])) {
1094 if ($fields[$fieldname] == $content) {
1095 unset($fields[$fieldname]);
1102 if (!$do_update || (count($fields) == 0)) {
1106 $sql = "UPDATE `".$table."` SET `".
1107 implode("` = ?, `", array_keys($fields))."` = ?".$condition_string;
1109 $params1 = array_values($fields);
1110 $params2 = array_values($condition);
1111 $params = array_merge_recursive($params1, $params2);
1113 return self::e($sql, $params);
1117 * @brief Select rows from a table
1119 * @param string $table Table name
1120 * @param array $fields array of selected fields
1121 * @param array $condition array of fields for condition
1122 * @param array $params array of several parameters
1124 * @return boolean|object If "limit" is equal "1" only a single row is returned, else a query object is returned
1128 * $fields = array("id", "uri", "uid", "network");
1130 * $condition = array("uid" => 1, "network" => 'dspr');
1132 * $condition = array("`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr');
1134 * $params = array("order" => array("id", "received" => true), "limit" => 1);
1136 * $data = dba::select($table, $fields, $condition, $params);
1138 public static function select($table, $fields = array(), $condition = array(), $params = array()) {
1143 if (count($fields) > 0) {
1144 $select_fields = "`".implode("`, `", array_values($fields))."`";
1146 $select_fields = "*";
1149 if (count($condition) > 0) {
1150 $array_element = each($condition);
1151 $array_key = $array_element['key'];
1152 if (is_int($array_key)) {
1153 $condition_string = " WHERE ".array_shift($condition);
1155 $condition_string = " WHERE `".implode("` = ? AND `", array_keys($condition))."` = ?";
1158 $condition_string = "";
1162 $single_row = false;
1164 if (isset($params['order'])) {
1165 $param_string .= " ORDER BY ";
1166 foreach ($params['order'] AS $fields => $order) {
1167 if (!is_int($fields)) {
1168 $param_string .= "`".$fields."` ".($order ? "DESC" : "ASC").", ";
1170 $param_string .= "`".$order."`, ";
1173 $param_string = substr($param_string, 0, -2);
1176 if (isset($params['limit']) && is_int($params['limit'])) {
1177 $param_string .= " LIMIT ".$params['limit'];
1178 $single_row = ($params['limit'] == 1);
1181 if (isset($params['only_query']) && $params['only_query']) {
1182 $single_row = !$params['only_query'];
1185 $sql = "SELECT ".$select_fields." FROM `".$table."`".$condition_string.$param_string;
1187 $result = self::p($sql, $condition);
1189 if (is_bool($result) || !$single_row) {
1192 $row = self::fetch($result);
1193 self::close($result);
1200 * @brief Fills an array with data from a query
1202 * @param object $stmt statement object
1203 * @return array Data array
1205 public static function inArray($stmt, $do_close = true) {
1206 if (is_bool($stmt)) {
1211 while ($row = self::fetch($stmt)) {
1221 * @brief Returns the error number of the last query
1223 * @return string Error number (0 if no error)
1225 public static function errorNo() {
1226 return self::$errorno;
1230 * @brief Returns the error message of the last query
1232 * @return string Error message ('' if no error)
1234 public static function errorMessage() {
1235 return self::$error;
1239 * @brief Closes the current statement
1241 * @param object $stmt statement object
1242 * @return boolean was the close successfull?
1244 public static function close($stmt) {
1245 if (!is_object($stmt)) {
1249 switch (self::$driver) {
1251 return $stmt->closeCursor();
1253 return $stmt->free_result();
1254 return $stmt->close();
1256 return mysql_free_result($stmt);
1261 function dbesc($str) {
1262 if (dba::$connected) {
1263 return(dba::escape($str));
1265 return(str_replace("'","\\'",$str));
1270 * @brief execute SQL query with printf style args - deprecated
1272 * Please use the dba:: functions instead:
1273 * dba::select, dba::exists, dba::insert
1274 * dba::delete, dba::update, dba::p, dba::e
1276 * @param $args Query parameters (1 to N parameters of different types)
1277 * @return array Query array
1280 $args = func_get_args();
1283 if (!dba::$connected) {
1287 $sql = dba::clean_query($sql);
1288 $sql = dba::any_value_fallback($sql);
1290 $stmt = @vsprintf($sql, $args);
1292 $ret = dba::p($stmt);
1294 if (is_bool($ret)) {
1298 $columns = dba::columnCount($ret);
1300 $data = dba::inArray($ret);
1302 if ((count($data) == 0) && ($columns == 0)) {
1309 function dba_timer() {
1310 return microtime(true);