2 use Friendica\Core\System;
3 use Friendica\Database\DBM;
4 use Friendica\Database\DBStructure;
6 require_once('include/datetime.php');
9 * @class MySQL database class
11 * This class is for the low level database stuff that does driver specific things.
15 public static $connected = true;
17 private static $_server_info = '';
19 private static $driver;
20 private static $error = false;
21 private static $errorno = 0;
22 private static $affected_rows = 0;
23 private static $in_transaction = false;
24 private static $relation = array();
26 public static function connect($serveraddr, $user, $pass, $db, $install = false) {
27 if (!is_null(self::$db)) {
33 $stamp1 = microtime(true);
35 $serveraddr = trim($serveraddr);
37 $serverdata = explode(':', $serveraddr);
38 $server = $serverdata[0];
40 if (count($serverdata) > 1) {
41 $port = trim($serverdata[1]);
44 $server = trim($server);
49 if (!(strlen($server) && strlen($user))) {
50 self::$connected = false;
56 if (strlen($server) && ($server !== 'localhost') && ($server !== '127.0.0.1')) {
57 if (! dns_get_record($server, DNS_A + DNS_CNAME + DNS_PTR)) {
58 self::$error = sprintf(t('Cannot locate DNS info for database server \'%s\''), $server);
59 self::$connected = false;
66 if (class_exists('\PDO') && in_array('mysql', PDO::getAvailableDrivers())) {
67 self::$driver = 'pdo';
68 $connect = "mysql:host=".$server.";dbname=".$db;
71 $connect .= ";port=".$port;
74 if (isset($a->config["system"]["db_charset"])) {
75 $connect .= ";charset=".$a->config["system"]["db_charset"];
78 self::$db = @new PDO($connect, $user, $pass);
79 self::$connected = true;
80 } catch (PDOException $e) {
81 self::$connected = false;
85 if (!self::$connected && class_exists('mysqli')) {
86 self::$driver = 'mysqli';
87 self::$db = @new mysqli($server, $user, $pass, $db, $port);
88 if (!mysqli_connect_errno()) {
89 self::$connected = true;
91 if (isset($a->config["system"]["db_charset"])) {
92 self::$db->set_charset($a->config["system"]["db_charset"]);
97 // No suitable SQL driver was found.
98 if (!self::$connected) {
101 System::unavailable();
104 $a->save_timestamp($stamp1, "network");
110 * @brief Returns the MySQL server version string
112 * This function discriminate between the deprecated mysql API and the current
113 * object-oriented mysqli API. Example of returned string: 5.5.46-0+deb8u1
117 public static function server_info() {
118 if (self::$_server_info == '') {
119 switch (self::$driver) {
121 self::$_server_info = self::$db->getAttribute(PDO::ATTR_SERVER_VERSION);
124 self::$_server_info = self::$db->server_info;
128 return self::$_server_info;
132 * @brief Returns the selected database name
136 public static function database_name() {
137 $ret = self::p("SELECT DATABASE() AS `db`");
138 $data = self::inArray($ret);
139 return $data[0]['db'];
143 * @brief Analyze a database query and log this if some conditions are met.
145 * @param string $query The database query that will be analyzed
147 private static function log_index($query) {
150 if (empty($a->config["system"]["db_log_index"])) {
154 // Don't explain an explain statement
155 if (strtolower(substr($query, 0, 7)) == "explain") {
159 // Only do the explain on "select", "update" and "delete"
160 if (!in_array(strtolower(substr($query, 0, 6)), array("select", "update", "delete"))) {
164 $r = self::p("EXPLAIN ".$query);
165 if (!DBM::is_result($r)) {
169 $watchlist = explode(',', $a->config["system"]["db_log_index_watch"]);
170 $blacklist = explode(',', $a->config["system"]["db_log_index_blacklist"]);
172 while ($row = dba::fetch($r)) {
173 if ((intval($a->config["system"]["db_loglimit_index"]) > 0)) {
174 $log = (in_array($row['key'], $watchlist) &&
175 ($row['rows'] >= intval($a->config["system"]["db_loglimit_index"])));
180 if ((intval($a->config["system"]["db_loglimit_index_high"]) > 0) && ($row['rows'] >= intval($a->config["system"]["db_loglimit_index_high"]))) {
184 if (in_array($row['key'], $blacklist) || ($row['key'] == "")) {
189 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
190 @file_put_contents($a->config["system"]["db_log_index"], datetime_convert()."\t".
191 $row['key']."\t".$row['rows']."\t".$row['Extra']."\t".
192 basename($backtrace[1]["file"])."\t".
193 $backtrace[1]["line"]."\t".$backtrace[2]["function"]."\t".
194 substr($query, 0, 2000)."\n", FILE_APPEND);
199 public static function escape($str) {
200 switch (self::$driver) {
202 return substr(@self::$db->quote($str, PDO::PARAM_STR), 1, -1);
204 return @self::$db->real_escape_string($str);
208 public static function connected() {
211 switch (self::$driver) {
213 $r = dba::p("SELECT 1");
214 if (DBM::is_result($r)) {
215 $row = dba::inArray($r);
216 $connected = ($row[0]['1'] == '1');
220 $connected = self::$db->ping();
227 * @brief Replaces ANY_VALUE() function by MIN() function,
228 * if the database server does not support ANY_VALUE().
230 * Considerations for Standard SQL, or MySQL with ONLY_FULL_GROUP_BY (default since 5.7.5).
231 * ANY_VALUE() is available from MySQL 5.7.5 https://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html
232 * A standard fall-back is to use MIN().
234 * @param string $sql An SQL string without the values
235 * @return string The input SQL string modified if necessary.
237 public static function any_value_fallback($sql) {
238 $server_info = self::server_info();
239 if (version_compare($server_info, '5.7.5', '<') ||
240 (stripos($server_info, 'MariaDB') !== false)) {
241 $sql = str_ireplace('ANY_VALUE(', 'MIN(', $sql);
247 * @brief beautifies the query - useful for "SHOW PROCESSLIST"
249 * This is safe when we bind the parameters later.
250 * The parameter values aren't part of the SQL.
252 * @param string $sql An SQL string without the values
253 * @return string The input SQL string modified if necessary.
255 public static function clean_query($sql) {
256 $search = array("\t", "\n", "\r", " ");
257 $replace = array(' ', ' ', ' ', ' ');
260 $sql = str_replace($search, $replace, $sql);
261 } while ($oldsql != $sql);
268 * @brief Replaces the ? placeholders with the parameters in the $args array
270 * @param string $sql SQL query
271 * @param array $args The parameters that are to replace the ? placeholders
272 * @return string The replaced SQL query
274 private static function replace_parameters($sql, $args) {
276 foreach ($args AS $param => $value) {
277 if (is_int($args[$param]) || is_float($args[$param])) {
278 $replace = intval($args[$param]);
280 $replace = "'".self::escape($args[$param])."'";
283 $pos = strpos($sql, '?', $offset);
284 if ($pos !== false) {
285 $sql = substr_replace($sql, $replace, $pos, 1);
287 $offset = $pos + strlen($replace);
293 * @brief Convert parameter array to an universal form
294 * @param array $args Parameter array
295 * @return array universalized parameter array
297 private static function getParam($args) {
300 // When the second function parameter is an array then use this as the parameter array
301 if ((count($args) > 0) && (is_array($args[1]))) {
309 * @brief Executes a prepared statement that returns data
310 * @usage Example: $r = p("SELECT * FROM `item` WHERE `guid` = ?", $guid);
312 * Please only use it with complicated queries.
313 * For all regular queries please use dba::select or dba::exists
315 * @param string $sql SQL statement
316 * @return object statement object
318 public static function p($sql) {
321 $stamp1 = microtime(true);
323 $params = self::getParam(func_get_args());
325 // Renumber the array keys to be sure that they fit
328 foreach ($params AS $param) {
329 // Avoid problems with some MySQL servers and boolean values. See issue #3645
330 if (is_bool($param)) {
331 $param = (int)$param;
333 $args[++$i] = $param;
336 if (!self::$connected) {
340 if ((substr_count($sql, '?') != count($args)) && (count($args) > 0)) {
341 // Question: Should we continue or stop the query here?
342 logger('Parameter mismatch. Query "'.$sql.'" - Parameters '.print_r($args, true), LOGGER_DEBUG);
345 $sql = self::clean_query($sql);
346 $sql = self::any_value_fallback($sql);
350 if (x($a->config,'system') && x($a->config['system'], 'db_callstack')) {
351 $sql = "/*".System::callstack()." */ ".$sql;
356 self::$affected_rows = 0;
358 // We have to make some things different if this function is called from "e"
359 $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2);
361 if (isset($trace[1])) {
362 $called_from = $trace[1];
364 // We use just something that is defined to avoid warnings
365 $called_from = $trace[0];
367 // We are having an own error logging in the function "e"
368 $called_from_e = ($called_from['function'] == 'e');
370 switch (self::$driver) {
372 // If there are no arguments we use "query"
373 if (count($args) == 0) {
374 if (!$retval = self::$db->query($sql)) {
375 $errorInfo = self::$db->errorInfo();
376 self::$error = $errorInfo[2];
377 self::$errorno = $errorInfo[1];
381 self::$affected_rows = $retval->rowCount();
385 if (!$stmt = self::$db->prepare($sql)) {
386 $errorInfo = self::$db->errorInfo();
387 self::$error = $errorInfo[2];
388 self::$errorno = $errorInfo[1];
393 foreach ($args AS $param => $value) {
394 $stmt->bindParam($param, $args[$param]);
397 if (!$stmt->execute()) {
398 $errorInfo = $stmt->errorInfo();
399 self::$error = $errorInfo[2];
400 self::$errorno = $errorInfo[1];
404 self::$affected_rows = $retval->rowCount();
408 // There are SQL statements that cannot be executed with a prepared statement
409 $parts = explode(' ', $orig_sql);
410 $command = strtolower($parts[0]);
411 $can_be_prepared = in_array($command, array('select', 'update', 'insert', 'delete'));
413 // The fallback routine is called as well when there are no arguments
414 if (!$can_be_prepared || (count($args) == 0)) {
415 $retval = self::$db->query(self::replace_parameters($sql, $args));
416 if (self::$db->errno) {
417 self::$error = self::$db->error;
418 self::$errorno = self::$db->errno;
421 if (isset($retval->num_rows)) {
422 self::$affected_rows = $retval->num_rows;
424 self::$affected_rows = self::$db->affected_rows;
430 $stmt = self::$db->stmt_init();
432 if (!$stmt->prepare($sql)) {
433 self::$error = $stmt->error;
434 self::$errorno = $stmt->errno;
441 foreach ($args AS $param => $value) {
442 if (is_int($args[$param])) {
444 } elseif (is_float($args[$param])) {
446 } elseif (is_string($args[$param])) {
451 $values[] = &$args[$param];
454 if (count($values) > 0) {
455 array_unshift($values, $params);
456 call_user_func_array(array($stmt, 'bind_param'), $values);
459 if (!$stmt->execute()) {
460 self::$error = self::$db->error;
461 self::$errorno = self::$db->errno;
464 $stmt->store_result();
466 self::$affected_rows = $retval->affected_rows;
471 // We are having an own error logging in the function "e"
472 if ((self::$errorno != 0) && !$called_from_e) {
473 // We have to preserve the error code, somewhere in the logging it get lost
474 $error = self::$error;
475 $errorno = self::$errorno;
477 logger('DB Error '.self::$errorno.': '.self::$error."\n".
478 System::callstack(8)."\n".self::replace_parameters($sql, $params));
480 self::$error = $error;
481 self::$errorno = $errorno;
484 $a->save_timestamp($stamp1, 'database');
486 if (x($a->config,'system') && x($a->config['system'], 'db_log')) {
488 $stamp2 = microtime(true);
489 $duration = (float)($stamp2 - $stamp1);
491 if (($duration > $a->config["system"]["db_loglimit"])) {
492 $duration = round($duration, 3);
493 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
495 @file_put_contents($a->config["system"]["db_log"], datetime_convert()."\t".$duration."\t".
496 basename($backtrace[1]["file"])."\t".
497 $backtrace[1]["line"]."\t".$backtrace[2]["function"]."\t".
498 substr(self::replace_parameters($sql, $args), 0, 2000)."\n", FILE_APPEND);
505 * @brief Executes a prepared statement like UPDATE or INSERT that doesn't return data
507 * Please use dba::delete, dba::insert, dba::update, ... instead
509 * @param string $sql SQL statement
510 * @return boolean Was the query successfull? False is returned only if an error occurred
512 public static function e($sql) {
515 $stamp = microtime(true);
517 $params = self::getParam(func_get_args());
519 // In a case of a deadlock we are repeating the query 20 times
523 $stmt = self::p($sql, $params);
525 if (is_bool($stmt)) {
527 } elseif (is_object($stmt)) {
535 } while ((self::$errorno == 1213) && (--$timeout > 0));
537 if (self::$errorno != 0) {
538 // We have to preserve the error code, somewhere in the logging it get lost
539 $error = self::$error;
540 $errorno = self::$errorno;
542 logger('DB Error '.self::$errorno.': '.self::$error."\n".
543 System::callstack(8)."\n".self::replace_parameters($sql, $params));
545 self::$error = $error;
546 self::$errorno = $errorno;
549 $a->save_timestamp($stamp, "database_write");
555 * @brief Check if data exists
557 * @param string $table Table name
558 * @param array $condition array of fields for condition
560 * @return boolean Are there rows for that condition?
562 public static function exists($table, $condition) {
569 $array_element = each($condition);
570 $array_key = $array_element['key'];
571 if (!is_int($array_key)) {
572 $fields = array($array_key);
575 $stmt = self::select($table, $fields, $condition, array('limit' => 1, 'only_query' => true));
577 if (is_bool($stmt)) {
580 $retval = (self::num_rows($stmt) > 0);
589 * @brief Fetches the first row
591 * Please use dba::select or dba::exists whenever this is possible.
593 * @param string $sql SQL statement
594 * @return array first row of query
596 public static function fetch_first($sql) {
597 $params = self::getParam(func_get_args());
599 $stmt = self::p($sql, $params);
601 if (is_bool($stmt)) {
604 $retval = self::fetch($stmt);
613 * @brief Returns the number of affected rows of the last statement
615 * @return int Number of rows
617 public static function affected_rows() {
618 return self::$affected_rows;
622 * @brief Returns the number of columns of a statement
624 * @param object Statement object
625 * @return int Number of columns
627 public static function columnCount($stmt) {
628 if (!is_object($stmt)) {
631 switch (self::$driver) {
633 return $stmt->columnCount();
635 return $stmt->field_count;
640 * @brief Returns the number of rows of a statement
642 * @param object Statement object
643 * @return int Number of rows
645 public static function num_rows($stmt) {
646 if (!is_object($stmt)) {
649 switch (self::$driver) {
651 return $stmt->rowCount();
653 return $stmt->num_rows;
659 * @brief Fetch a single row
661 * @param object $stmt statement object
662 * @return array current row
664 public static function fetch($stmt) {
665 if (!is_object($stmt)) {
669 switch (self::$driver) {
671 return $stmt->fetch(PDO::FETCH_ASSOC);
673 if (get_class($stmt) == 'mysqli_result') {
674 return $stmt->fetch_assoc();
677 // This code works, but is slow
679 // Bind the result to a result array
683 for ($x = 0; $x < $stmt->field_count; $x++) {
684 $cols[] = &$cols_num[$x];
687 call_user_func_array(array($stmt, 'bind_result'), $cols);
689 if (!$stmt->fetch()) {
694 // We need to get the field names for the array keys
695 // It seems that there is no better way to do this.
696 $result = $stmt->result_metadata();
697 $fields = $result->fetch_fields();
700 foreach ($cols_num AS $param => $col) {
701 $columns[$fields[$param]->name] = $col;
708 * @brief Insert a row into a table
710 * @param string $table Table name
711 * @param array $param parameter array
712 * @param bool $on_duplicate_update Do an update on a duplicate entry
714 * @return boolean was the insert successfull?
716 public static function insert($table, $param, $on_duplicate_update = false) {
718 if (empty($table) || empty($param)) {
719 logger('Table and fields have to be set');
723 $sql = "INSERT INTO `".self::escape($table)."` (`".implode("`, `", array_keys($param))."`) VALUES (".
724 substr(str_repeat("?, ", count($param)), 0, -2).")";
726 if ($on_duplicate_update) {
727 $sql .= " ON DUPLICATE KEY UPDATE `".implode("` = ?, `", array_keys($param))."` = ?";
729 $values = array_values($param);
730 $param = array_merge_recursive($values, $values);
733 return self::e($sql, $param);
737 * @brief Fetch the id of the last insert command
739 * @return integer Last inserted id
741 public static function lastInsertId() {
742 switch (self::$driver) {
744 $id = self::$db->lastInsertId();
747 $id = self::$db->insert_id;
754 * @brief Locks a table for exclusive write access
756 * This function can be extended in the future to accept a table array as well.
758 * @param string $table Table name
760 * @return boolean was the lock successful?
762 public static function lock($table) {
763 // See here: https://dev.mysql.com/doc/refman/5.7/en/lock-tables-and-transactions.html
764 self::e("SET autocommit=0");
765 $success = self::e("LOCK TABLES `".self::escape($table)."` WRITE");
767 self::e("SET autocommit=1");
769 self::$in_transaction = true;
775 * @brief Unlocks all locked tables
777 * @return boolean was the unlock successful?
779 public static function unlock() {
780 // See here: https://dev.mysql.com/doc/refman/5.7/en/lock-tables-and-transactions.html
782 $success = self::e("UNLOCK TABLES");
783 self::e("SET autocommit=1");
784 self::$in_transaction = false;
789 * @brief Starts a transaction
791 * @return boolean Was the command executed successfully?
793 public static function transaction() {
794 if (!self::e('COMMIT')) {
797 if (!self::e('START TRANSACTION')) {
800 self::$in_transaction = true;
805 * @brief Does a commit
807 * @return boolean Was the command executed successfully?
809 public static function commit() {
810 if (!self::e('COMMIT')) {
813 self::$in_transaction = false;
818 * @brief Does a rollback
820 * @return boolean Was the command executed successfully?
822 public static function rollback() {
823 if (!self::e('ROLLBACK')) {
826 self::$in_transaction = false;
831 * @brief Build the array with the table relations
833 * The array is build from the database definitions in DBStructure.php
835 * This process must only be started once, since the value is cached.
837 private static function build_relation_data() {
838 $definition = DBStructure::definition();
840 foreach ($definition AS $table => $structure) {
841 foreach ($structure['fields'] AS $field => $field_struct) {
842 if (isset($field_struct['relation'])) {
843 foreach ($field_struct['relation'] AS $rel_table => $rel_field) {
844 self::$relation[$rel_table][$rel_field][$table][] = $field;
852 * @brief Delete a row from a table
854 * @param string $table Table name
855 * @param array $param parameter array
856 * @param boolean $in_process Internal use: Only do a commit after the last delete
857 * @param array $callstack Internal use: prevent endless loops
859 * @return boolean|array was the delete successfull? When $in_process is set: deletion data
861 public static function delete($table, $param, $in_process = false, &$callstack = array()) {
863 if (empty($table) || empty($param)) {
864 logger('Table and condition have to be set');
870 // Create a key for the loop prevention
871 $key = $table.':'.implode(':', array_keys($param)).':'.implode(':', $param);
873 // We quit when this key already exists in the callstack.
874 if (isset($callstack[$key])) {
878 $callstack[$key] = true;
880 $table = self::escape($table);
882 $commands[$key] = array('table' => $table, 'param' => $param);
884 // To speed up the whole process we cache the table relations
885 if (count(self::$relation) == 0) {
886 self::build_relation_data();
889 // Is there a relation entry for the table?
890 if (isset(self::$relation[$table])) {
891 // We only allow a simple "one field" relation.
892 $field = array_keys(self::$relation[$table])[0];
893 $rel_def = array_values(self::$relation[$table])[0];
895 // Create a key for preventing double queries
896 $qkey = $field.'-'.$table.':'.implode(':', array_keys($param)).':'.implode(':', $param);
898 // When the search field is the relation field, we don't need to fetch the rows
899 // This is useful when the leading record is already deleted in the frontend but the rest is done in the backend
900 if ((count($param) == 1) && ($field == array_keys($param)[0])) {
901 foreach ($rel_def AS $rel_table => $rel_fields) {
902 foreach ($rel_fields AS $rel_field) {
903 $retval = self::delete($rel_table, array($rel_field => array_values($param)[0]), true, $callstack);
904 $commands = array_merge($commands, $retval);
907 // We quit when this key already exists in the callstack.
908 } elseif (!isset($callstack[$qkey])) {
910 $callstack[$qkey] = true;
912 // Fetch all rows that are to be deleted
913 $data = self::select($table, array($field), $param);
915 while ($row = self::fetch($data)) {
916 // Now we accumulate the delete commands
917 $retval = self::delete($table, array($field => $row[$field]), true, $callstack);
918 $commands = array_merge($commands, $retval);
923 // Since we had split the delete command we don't need the original command anymore
924 unset($commands[$key]);
929 // Now we finalize the process
930 $do_transaction = !self::$in_transaction;
932 if ($do_transaction) {
936 $compacted = array();
939 foreach ($commands AS $command) {
940 $condition = $command['param'];
941 $array_element = each($condition);
942 $array_key = $array_element['key'];
943 if (is_int($array_key)) {
944 $condition_string = " WHERE ".array_shift($condition);
946 $condition_string = " WHERE `".implode("` = ? AND `", array_keys($condition))."` = ?";
949 if ((count($command['param']) > 1) || is_int($array_key)) {
950 $sql = "DELETE FROM `".$command['table']."`".$condition_string;
951 logger(self::replace_parameters($sql, $condition), LOGGER_DATA);
953 if (!self::e($sql, $condition)) {
954 if ($do_transaction) {
960 $key_table = $command['table'];
961 $key_param = array_keys($command['param'])[0];
962 $value = array_values($command['param'])[0];
964 // Split the SQL queries in chunks of 100 values
965 // We do the $i stuff here to make the code better readable
966 $i = $counter[$key_table][$key_param];
967 if (count($compacted[$key_table][$key_param][$i]) > 100) {
971 $compacted[$key_table][$key_param][$i][$value] = $value;
972 $counter[$key_table][$key_param] = $i;
975 foreach ($compacted AS $table => $values) {
976 foreach ($values AS $field => $field_value_list) {
977 foreach ($field_value_list AS $field_values) {
978 $sql = "DELETE FROM `".$table."` WHERE `".$field."` IN (".
979 substr(str_repeat("?, ", count($field_values)), 0, -2).");";
981 logger(self::replace_parameters($sql, $field_values), LOGGER_DATA);
983 if (!self::e($sql, $field_values)) {
984 if ($do_transaction) {
992 if ($do_transaction) {
1002 * @brief Updates rows
1004 * Updates rows in the database. When $old_fields is set to an array,
1005 * the system will only do an update if the fields in that array changed.
1008 * Only the values in $old_fields are compared.
1009 * This is an intentional behaviour.
1012 * We include the timestamp field in $fields but not in $old_fields.
1013 * Then the row will only get the new timestamp when the other fields had changed.
1015 * When $old_fields is set to a boolean value the system will do this compare itself.
1016 * When $old_fields is set to "true" the system will do an insert if the row doesn't exists.
1019 * Only set $old_fields to a boolean value when you are sure that you will update a single row.
1020 * When you set $old_fields to "true" then $fields must contain all relevant fields!
1022 * @param string $table Table name
1023 * @param array $fields contains the fields that are updated
1024 * @param array $condition condition array with the key values
1025 * @param array|boolean $old_fields array with the old field values that are about to be replaced (true = update on duplicate)
1027 * @return boolean was the update successfull?
1029 public static function update($table, $fields, $condition, $old_fields = array()) {
1031 if (empty($table) || empty($fields) || empty($condition)) {
1032 logger('Table, fields and condition have to be set');
1036 $table = self::escape($table);
1038 $array_element = each($condition);
1039 $array_key = $array_element['key'];
1040 if (is_int($array_key)) {
1041 $condition_string = " WHERE ".array_shift($condition);
1043 $condition_string = " WHERE `".implode("` = ? AND `", array_keys($condition))."` = ?";
1046 if (is_bool($old_fields)) {
1047 $do_insert = $old_fields;
1049 $old_fields = self::select($table, array(), $condition, array('limit' => 1));
1051 if (is_bool($old_fields)) {
1053 $values = array_merge($condition, $fields);
1054 return self::insert($table, $values, $do_insert);
1056 $old_fields = array();
1060 $do_update = (count($old_fields) == 0);
1062 foreach ($old_fields AS $fieldname => $content) {
1063 if (isset($fields[$fieldname])) {
1064 if ($fields[$fieldname] == $content) {
1065 unset($fields[$fieldname]);
1072 if (!$do_update || (count($fields) == 0)) {
1076 $sql = "UPDATE `".$table."` SET `".
1077 implode("` = ?, `", array_keys($fields))."` = ?".$condition_string;
1079 $params1 = array_values($fields);
1080 $params2 = array_values($condition);
1081 $params = array_merge_recursive($params1, $params2);
1083 return self::e($sql, $params);
1087 * @brief Select rows from a table
1089 * @param string $table Table name
1090 * @param array $fields array of selected fields
1091 * @param array $condition array of fields for condition
1092 * @param array $params array of several parameters
1094 * @return boolean|object If "limit" is equal "1" only a single row is returned, else a query object is returned
1098 * $fields = array("id", "uri", "uid", "network");
1100 * $condition = array("uid" => 1, "network" => 'dspr');
1102 * $condition = array("`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr');
1104 * $params = array("order" => array("id", "received" => true), "limit" => 1);
1106 * $data = dba::select($table, $fields, $condition, $params);
1108 public static function select($table, array $fields = [], array $condition = [], array $params = [])
1114 if (count($fields) > 0) {
1115 $select_fields = "`".implode("`, `", array_values($fields))."`";
1117 $select_fields = "*";
1120 $condition_string = self::buildCondition($condition);
1123 $single_row = false;
1125 if (isset($params['order'])) {
1126 $param_string .= " ORDER BY ";
1127 foreach ($params['order'] AS $fields => $order) {
1128 if (!is_int($fields)) {
1129 $param_string .= "`".$fields."` ".($order ? "DESC" : "ASC").", ";
1131 $param_string .= "`".$order."`, ";
1134 $param_string = substr($param_string, 0, -2);
1137 if (isset($params['limit']) && is_int($params['limit'])) {
1138 $param_string .= " LIMIT ".$params['limit'];
1139 $single_row = ($params['limit'] == 1);
1142 if (isset($params['limit']) && is_array($params['limit'])) {
1143 $param_string .= " LIMIT ".intval($params['limit'][0]).", ".intval($params['limit'][1]);
1144 $single_row = ($params['limit'][1] == 1);
1147 if (isset($params['only_query']) && $params['only_query']) {
1148 $single_row = !$params['only_query'];
1151 $sql = "SELECT ".$select_fields." FROM `".$table."`".$condition_string.$param_string;
1153 $result = self::p($sql, $condition);
1155 if (is_bool($result) || !$single_row) {
1158 $row = self::fetch($result);
1159 self::close($result);
1165 * @brief Counts the rows from a table satisfying the provided condition
1167 * @param string $table Table name
1168 * @param array $condition array of fields for condition
1175 * $condition = ["uid" => 1, "network" => 'dspr'];
1177 * $condition = ["`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr'];
1179 * $count = dba::count($table, $condition);
1181 public static function count($table, array $condition = [])
1187 $condition_string = self::buildCondition($condition);
1189 $sql = "SELECT COUNT(*) AS `count` FROM `".$table."`".$condition_string;
1191 $row = self::fetch_first($sql, $condition);
1193 return $row['count'];
1197 * @brief Returns the SQL condition string built from the provided condition array
1199 * This function operates with two modes.
1200 * - Supplied with a filed/value associative array, it builds simple strict
1201 * equality conditions linked by AND.
1202 * - Supplied with a flat list, the first element is the condition string and
1203 * the following arguments are the values to be interpolated
1205 * $condition = ["uid" => 1, "network" => 'dspr'];
1207 * $condition = ["`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr'];
1209 * In either case, the provided array is left with the parameters only
1211 * @param array $condition
1214 private static function buildCondition(array &$condition = [])
1216 $condition_string = '';
1217 if (count($condition) > 0) {
1218 $array_element = each($condition);
1219 $array_key = $array_element['key'];
1220 if (is_int($array_key)) {
1221 $condition_string = " WHERE ".array_shift($condition);
1223 $condition_string = " WHERE `".implode("` = ? AND `", array_keys($condition))."` = ?";
1227 return $condition_string;
1231 * @brief Fills an array with data from a query
1233 * @param object $stmt statement object
1234 * @return array Data array
1236 public static function inArray($stmt, $do_close = true) {
1237 if (is_bool($stmt)) {
1242 while ($row = self::fetch($stmt)) {
1252 * @brief Returns the error number of the last query
1254 * @return string Error number (0 if no error)
1256 public static function errorNo() {
1257 return self::$errorno;
1261 * @brief Returns the error message of the last query
1263 * @return string Error message ('' if no error)
1265 public static function errorMessage() {
1266 return self::$error;
1270 * @brief Closes the current statement
1272 * @param object $stmt statement object
1273 * @return boolean was the close successfull?
1275 public static function close($stmt) {
1276 if (!is_object($stmt)) {
1280 switch (self::$driver) {
1282 return $stmt->closeCursor();
1284 $stmt->free_result();
1285 return $stmt->close();
1290 function dbesc($str) {
1291 if (dba::$connected) {
1292 return(dba::escape($str));
1294 return(str_replace("'","\\'",$str));
1299 * @brief execute SQL query with printf style args - deprecated
1301 * Please use the dba:: functions instead:
1302 * dba::select, dba::exists, dba::insert
1303 * dba::delete, dba::update, dba::p, dba::e
1305 * @param $args Query parameters (1 to N parameters of different types)
1306 * @return array Query array
1309 $args = func_get_args();
1312 if (!dba::$connected) {
1316 $sql = dba::clean_query($sql);
1317 $sql = dba::any_value_fallback($sql);
1319 $stmt = @vsprintf($sql, $args);
1321 $ret = dba::p($stmt);
1323 if (is_bool($ret)) {
1327 $columns = dba::columnCount($ret);
1329 $data = dba::inArray($ret);
1331 if ((count($data) == 0) && ($columns == 0)) {
1338 function dba_timer() {
1339 return microtime(true);