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 // No suitable SQL driver was found.
97 if (!self::$connected) {
100 system_unavailable();
103 $a->save_timestamp($stamp1, "network");
109 * @brief Returns the MySQL server version string
111 * This function discriminate between the deprecated mysql API and the current
112 * object-oriented mysqli API. Example of returned string: 5.5.46-0+deb8u1
116 public static function server_info() {
117 if (self::$_server_info == '') {
118 switch (self::$driver) {
120 self::$_server_info = self::$db->getAttribute(PDO::ATTR_SERVER_VERSION);
123 self::$_server_info = self::$db->server_info;
127 return self::$_server_info;
131 * @brief Returns the selected database name
135 public static function database_name() {
136 $ret = self::p("SELECT DATABASE() AS `db`");
137 $data = self::inArray($ret);
138 return $data[0]['db'];
142 * @brief Analyze a database query and log this if some conditions are met.
144 * @param string $query The database query that will be analyzed
146 private static function log_index($query) {
149 if (empty($a->config["system"]["db_log_index"])) {
153 // Don't explain an explain statement
154 if (strtolower(substr($query, 0, 7)) == "explain") {
158 // Only do the explain on "select", "update" and "delete"
159 if (!in_array(strtolower(substr($query, 0, 6)), array("select", "update", "delete"))) {
163 $r = self::p("EXPLAIN ".$query);
164 if (!DBM::is_result($r)) {
168 $watchlist = explode(',', $a->config["system"]["db_log_index_watch"]);
169 $blacklist = explode(',', $a->config["system"]["db_log_index_blacklist"]);
171 while ($row = dba::fetch($r)) {
172 if ((intval($a->config["system"]["db_loglimit_index"]) > 0)) {
173 $log = (in_array($row['key'], $watchlist) &&
174 ($row['rows'] >= intval($a->config["system"]["db_loglimit_index"])));
179 if ((intval($a->config["system"]["db_loglimit_index_high"]) > 0) && ($row['rows'] >= intval($a->config["system"]["db_loglimit_index_high"]))) {
183 if (in_array($row['key'], $blacklist) || ($row['key'] == "")) {
188 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
189 @file_put_contents($a->config["system"]["db_log_index"], datetime_convert()."\t".
190 $row['key']."\t".$row['rows']."\t".$row['Extra']."\t".
191 basename($backtrace[1]["file"])."\t".
192 $backtrace[1]["line"]."\t".$backtrace[2]["function"]."\t".
193 substr($query, 0, 2000)."\n", FILE_APPEND);
198 public static function escape($str) {
199 switch (self::$driver) {
201 return substr(@self::$db->quote($str, PDO::PARAM_STR), 1, -1);
203 return @self::$db->real_escape_string($str);
207 public static function connected() {
210 switch (self::$driver) {
212 $r = dba::p("SELECT 1");
213 if (DBM::is_result($r)) {
214 $row = dba::inArray($r);
215 $connected = ($row[0]['1'] == '1');
219 $connected = self::$db->ping();
226 * @brief Replaces ANY_VALUE() function by MIN() function,
227 * if the database server does not support ANY_VALUE().
229 * Considerations for Standard SQL, or MySQL with ONLY_FULL_GROUP_BY (default since 5.7.5).
230 * ANY_VALUE() is available from MySQL 5.7.5 https://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html
231 * A standard fall-back is to use MIN().
233 * @param string $sql An SQL string without the values
234 * @return string The input SQL string modified if necessary.
236 public static function any_value_fallback($sql) {
237 $server_info = self::server_info();
238 if (version_compare($server_info, '5.7.5', '<') ||
239 (stripos($server_info, 'MariaDB') !== false)) {
240 $sql = str_ireplace('ANY_VALUE(', 'MIN(', $sql);
246 * @brief beautifies the query - useful for "SHOW PROCESSLIST"
248 * This is safe when we bind the parameters later.
249 * The parameter values aren't part of the SQL.
251 * @param string $sql An SQL string without the values
252 * @return string The input SQL string modified if necessary.
254 public static function clean_query($sql) {
255 $search = array("\t", "\n", "\r", " ");
256 $replace = array(' ', ' ', ' ', ' ');
259 $sql = str_replace($search, $replace, $sql);
260 } while ($oldsql != $sql);
267 * @brief Replaces the ? placeholders with the parameters in the $args array
269 * @param string $sql SQL query
270 * @param array $args The parameters that are to replace the ? placeholders
271 * @return string The replaced SQL query
273 private static function replace_parameters($sql, $args) {
275 foreach ($args AS $param => $value) {
276 if (is_int($args[$param]) || is_float($args[$param])) {
277 $replace = intval($args[$param]);
279 $replace = "'".self::escape($args[$param])."'";
282 $pos = strpos($sql, '?', $offset);
283 if ($pos !== false) {
284 $sql = substr_replace($sql, $replace, $pos, 1);
286 $offset = $pos + strlen($replace);
292 * @brief Convert parameter array to an universal form
293 * @param array $args Parameter array
294 * @return array universalized parameter array
296 private static function getParam($args) {
299 // When the second function parameter is an array then use this as the parameter array
300 if ((count($args) > 0) && (is_array($args[1]))) {
308 * @brief Executes a prepared statement that returns data
309 * @usage Example: $r = p("SELECT * FROM `item` WHERE `guid` = ?", $guid);
311 * Please only use it with complicated queries.
312 * For all regular queries please use dba::select or dba::exists
314 * @param string $sql SQL statement
315 * @return object statement object
317 public static function p($sql) {
320 $stamp1 = microtime(true);
322 $params = self::getParam(func_get_args());
324 // Renumber the array keys to be sure that they fit
327 foreach ($params AS $param) {
328 // Avoid problems with some MySQL servers and boolean values. See issue #3645
329 if (is_bool($param)) {
330 $param = (int)$param;
332 $args[++$i] = $param;
335 if (!self::$connected) {
339 if ((substr_count($sql, '?') != count($args)) && (count($args) > 0)) {
340 // Question: Should we continue or stop the query here?
341 logger('Parameter mismatch. Query "'.$sql.'" - Parameters '.print_r($args, true), LOGGER_DEBUG);
344 $sql = self::clean_query($sql);
345 $sql = self::any_value_fallback($sql);
349 if (x($a->config,'system') && x($a->config['system'], 'db_callstack')) {
350 $sql = "/*".System::callstack()." */ ".$sql;
355 self::$affected_rows = 0;
357 // We have to make some things different if this function is called from "e"
358 $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2);
360 if (isset($trace[1])) {
361 $called_from = $trace[1];
363 // We use just something that is defined to avoid warnings
364 $called_from = $trace[0];
366 // We are having an own error logging in the function "e"
367 $called_from_e = ($called_from['function'] == 'e');
369 switch (self::$driver) {
371 // If there are no arguments we use "query"
372 if (count($args) == 0) {
373 if (!$retval = self::$db->query($sql)) {
374 $errorInfo = self::$db->errorInfo();
375 self::$error = $errorInfo[2];
376 self::$errorno = $errorInfo[1];
380 self::$affected_rows = $retval->rowCount();
384 if (!$stmt = self::$db->prepare($sql)) {
385 $errorInfo = self::$db->errorInfo();
386 self::$error = $errorInfo[2];
387 self::$errorno = $errorInfo[1];
392 foreach ($args AS $param => $value) {
393 $stmt->bindParam($param, $args[$param]);
396 if (!$stmt->execute()) {
397 $errorInfo = $stmt->errorInfo();
398 self::$error = $errorInfo[2];
399 self::$errorno = $errorInfo[1];
403 self::$affected_rows = $retval->rowCount();
407 // There are SQL statements that cannot be executed with a prepared statement
408 $parts = explode(' ', $orig_sql);
409 $command = strtolower($parts[0]);
410 $can_be_prepared = in_array($command, array('select', 'update', 'insert', 'delete'));
412 // The fallback routine is called as well when there are no arguments
413 if (!$can_be_prepared || (count($args) == 0)) {
414 $retval = self::$db->query(self::replace_parameters($sql, $args));
415 if (self::$db->errno) {
416 self::$error = self::$db->error;
417 self::$errorno = self::$db->errno;
420 if (isset($retval->num_rows)) {
421 self::$affected_rows = $retval->num_rows;
423 self::$affected_rows = self::$db->affected_rows;
429 $stmt = self::$db->stmt_init();
431 if (!$stmt->prepare($sql)) {
432 self::$error = $stmt->error;
433 self::$errorno = $stmt->errno;
440 foreach ($args AS $param => $value) {
441 if (is_int($args[$param])) {
443 } elseif (is_float($args[$param])) {
445 } elseif (is_string($args[$param])) {
450 $values[] = &$args[$param];
453 if (count($values) > 0) {
454 array_unshift($values, $params);
455 call_user_func_array(array($stmt, 'bind_param'), $values);
458 if (!$stmt->execute()) {
459 self::$error = self::$db->error;
460 self::$errorno = self::$db->errno;
463 $stmt->store_result();
465 self::$affected_rows = $retval->affected_rows;
470 // We are having an own error logging in the function "e"
471 if ((self::$errorno != 0) && !$called_from_e) {
472 // We have to preserve the error code, somewhere in the logging it get lost
473 $error = self::$error;
474 $errorno = self::$errorno;
476 logger('DB Error '.self::$errorno.': '.self::$error."\n".
477 System::callstack(8)."\n".self::replace_parameters($sql, $params));
479 self::$error = $error;
480 self::$errorno = $errorno;
483 $a->save_timestamp($stamp1, 'database');
485 if (x($a->config,'system') && x($a->config['system'], 'db_log')) {
487 $stamp2 = microtime(true);
488 $duration = (float)($stamp2 - $stamp1);
490 if (($duration > $a->config["system"]["db_loglimit"])) {
491 $duration = round($duration, 3);
492 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
494 @file_put_contents($a->config["system"]["db_log"], datetime_convert()."\t".$duration."\t".
495 basename($backtrace[1]["file"])."\t".
496 $backtrace[1]["line"]."\t".$backtrace[2]["function"]."\t".
497 substr(self::replace_parameters($sql, $args), 0, 2000)."\n", FILE_APPEND);
504 * @brief Executes a prepared statement like UPDATE or INSERT that doesn't return data
506 * Please use dba::delete, dba::insert, dba::update, ... instead
508 * @param string $sql SQL statement
509 * @return boolean Was the query successfull? False is returned only if an error occurred
511 public static function e($sql) {
514 $stamp = microtime(true);
516 $params = self::getParam(func_get_args());
518 // In a case of a deadlock we are repeating the query 20 times
522 $stmt = self::p($sql, $params);
524 if (is_bool($stmt)) {
526 } elseif (is_object($stmt)) {
534 } while ((self::$errorno == 1213) && (--$timeout > 0));
536 if (self::$errorno != 0) {
537 // We have to preserve the error code, somewhere in the logging it get lost
538 $error = self::$error;
539 $errorno = self::$errorno;
541 logger('DB Error '.self::$errorno.': '.self::$error."\n".
542 System::callstack(8)."\n".self::replace_parameters($sql, $params));
544 self::$error = $error;
545 self::$errorno = $errorno;
548 $a->save_timestamp($stamp, "database_write");
554 * @brief Check if data exists
556 * @param string $table Table name
557 * @param array $condition array of fields for condition
559 * @return boolean Are there rows for that condition?
561 public static function exists($table, $condition) {
568 $array_element = each($condition);
569 $array_key = $array_element['key'];
570 if (!is_int($array_key)) {
571 $fields = array($array_key);
574 $stmt = self::select($table, $fields, $condition, array('limit' => 1, 'only_query' => true));
576 if (is_bool($stmt)) {
579 $retval = (self::num_rows($stmt) > 0);
588 * @brief Fetches the first row
590 * Please use dba::select or dba::exists whenever this is possible.
592 * @param string $sql SQL statement
593 * @return array first row of query
595 public static function fetch_first($sql) {
596 $params = self::getParam(func_get_args());
598 $stmt = self::p($sql, $params);
600 if (is_bool($stmt)) {
603 $retval = self::fetch($stmt);
612 * @brief Returns the number of affected rows of the last statement
614 * @return int Number of rows
616 public static function affected_rows() {
617 return self::$affected_rows;
621 * @brief Returns the number of columns of a statement
623 * @param object Statement object
624 * @return int Number of columns
626 public static function columnCount($stmt) {
627 if (!is_object($stmt)) {
630 switch (self::$driver) {
632 return $stmt->columnCount();
634 return $stmt->field_count;
639 * @brief Returns the number of rows of a statement
641 * @param object Statement object
642 * @return int Number of rows
644 public static function num_rows($stmt) {
645 if (!is_object($stmt)) {
648 switch (self::$driver) {
650 return $stmt->rowCount();
652 return $stmt->num_rows;
658 * @brief Fetch a single row
660 * @param object $stmt statement object
661 * @return array current row
663 public static function fetch($stmt) {
664 if (!is_object($stmt)) {
668 switch (self::$driver) {
670 return $stmt->fetch(PDO::FETCH_ASSOC);
672 if (get_class($stmt) == 'mysqli_result') {
673 return $stmt->fetch_assoc();
676 // This code works, but is slow
678 // Bind the result to a result array
682 for ($x = 0; $x < $stmt->field_count; $x++) {
683 $cols[] = &$cols_num[$x];
686 call_user_func_array(array($stmt, 'bind_result'), $cols);
688 if (!$stmt->fetch()) {
693 // We need to get the field names for the array keys
694 // It seems that there is no better way to do this.
695 $result = $stmt->result_metadata();
696 $fields = $result->fetch_fields();
699 foreach ($cols_num AS $param => $col) {
700 $columns[$fields[$param]->name] = $col;
707 * @brief Insert a row into a table
709 * @param string $table Table name
710 * @param array $param parameter array
711 * @param bool $on_duplicate_update Do an update on a duplicate entry
713 * @return boolean was the insert successfull?
715 public static function insert($table, $param, $on_duplicate_update = false) {
717 if (empty($table) || empty($param)) {
718 logger('Table and fields have to be set');
722 $sql = "INSERT INTO `".self::escape($table)."` (`".implode("`, `", array_keys($param))."`) VALUES (".
723 substr(str_repeat("?, ", count($param)), 0, -2).")";
725 if ($on_duplicate_update) {
726 $sql .= " ON DUPLICATE KEY UPDATE `".implode("` = ?, `", array_keys($param))."` = ?";
728 $values = array_values($param);
729 $param = array_merge_recursive($values, $values);
732 return self::e($sql, $param);
736 * @brief Fetch the id of the last insert command
738 * @return integer Last inserted id
740 public static function lastInsertId() {
741 switch (self::$driver) {
743 $id = self::$db->lastInsertId();
746 $id = self::$db->insert_id;
753 * @brief Locks a table for exclusive write access
755 * This function can be extended in the future to accept a table array as well.
757 * @param string $table Table name
759 * @return boolean was the lock successful?
761 public static function lock($table) {
762 // See here: https://dev.mysql.com/doc/refman/5.7/en/lock-tables-and-transactions.html
763 self::e("SET autocommit=0");
764 $success = self::e("LOCK TABLES `".self::escape($table)."` WRITE");
766 self::e("SET autocommit=1");
768 self::$in_transaction = true;
774 * @brief Unlocks all locked tables
776 * @return boolean was the unlock successful?
778 public static function unlock() {
779 // See here: https://dev.mysql.com/doc/refman/5.7/en/lock-tables-and-transactions.html
781 $success = self::e("UNLOCK TABLES");
782 self::e("SET autocommit=1");
783 self::$in_transaction = false;
788 * @brief Starts a transaction
790 * @return boolean Was the command executed successfully?
792 public static function transaction() {
793 if (!self::e('COMMIT')) {
796 if (!self::e('START TRANSACTION')) {
799 self::$in_transaction = true;
804 * @brief Does a commit
806 * @return boolean Was the command executed successfully?
808 public static function commit() {
809 if (!self::e('COMMIT')) {
812 self::$in_transaction = false;
817 * @brief Does a rollback
819 * @return boolean Was the command executed successfully?
821 public static function rollback() {
822 if (!self::e('ROLLBACK')) {
825 self::$in_transaction = false;
830 * @brief Build the array with the table relations
832 * The array is build from the database definitions in dbstructure.php
834 * This process must only be started once, since the value is cached.
836 private static function build_relation_data() {
837 $definition = db_definition();
839 foreach ($definition AS $table => $structure) {
840 foreach ($structure['fields'] AS $field => $field_struct) {
841 if (isset($field_struct['relation'])) {
842 foreach ($field_struct['relation'] AS $rel_table => $rel_field) {
843 self::$relation[$rel_table][$rel_field][$table][] = $field;
851 * @brief Delete a row from a table
853 * @param string $table Table name
854 * @param array $param parameter array
855 * @param boolean $in_process Internal use: Only do a commit after the last delete
856 * @param array $callstack Internal use: prevent endless loops
858 * @return boolean|array was the delete successfull? When $in_process is set: deletion data
860 public static function delete($table, $param, $in_process = false, &$callstack = array()) {
862 if (empty($table) || empty($param)) {
863 logger('Table and condition have to be set');
869 // Create a key for the loop prevention
870 $key = $table.':'.implode(':', array_keys($param)).':'.implode(':', $param);
872 // We quit when this key already exists in the callstack.
873 if (isset($callstack[$key])) {
877 $callstack[$key] = true;
879 $table = self::escape($table);
881 $commands[$key] = array('table' => $table, 'param' => $param);
883 // To speed up the whole process we cache the table relations
884 if (count(self::$relation) == 0) {
885 self::build_relation_data();
888 // Is there a relation entry for the table?
889 if (isset(self::$relation[$table])) {
890 // We only allow a simple "one field" relation.
891 $field = array_keys(self::$relation[$table])[0];
892 $rel_def = array_values(self::$relation[$table])[0];
894 // Create a key for preventing double queries
895 $qkey = $field.'-'.$table.':'.implode(':', array_keys($param)).':'.implode(':', $param);
897 // When the search field is the relation field, we don't need to fetch the rows
898 // This is useful when the leading record is already deleted in the frontend but the rest is done in the backend
899 if ((count($param) == 1) && ($field == array_keys($param)[0])) {
900 foreach ($rel_def AS $rel_table => $rel_fields) {
901 foreach ($rel_fields AS $rel_field) {
902 $retval = self::delete($rel_table, array($rel_field => array_values($param)[0]), true, $callstack);
903 $commands = array_merge($commands, $retval);
906 // We quit when this key already exists in the callstack.
907 } elseif (!isset($callstack[$qkey])) {
909 $callstack[$qkey] = true;
911 // Fetch all rows that are to be deleted
912 $data = self::select($table, array($field), $param);
914 while ($row = self::fetch($data)) {
915 // Now we accumulate the delete commands
916 $retval = self::delete($table, array($field => $row[$field]), true, $callstack);
917 $commands = array_merge($commands, $retval);
922 // Since we had split the delete command we don't need the original command anymore
923 unset($commands[$key]);
928 // Now we finalize the process
929 $do_transaction = !self::$in_transaction;
931 if ($do_transaction) {
935 $compacted = array();
938 foreach ($commands AS $command) {
939 $condition = $command['param'];
940 $array_element = each($condition);
941 $array_key = $array_element['key'];
942 if (is_int($array_key)) {
943 $condition_string = " WHERE ".array_shift($condition);
945 $condition_string = " WHERE `".implode("` = ? AND `", array_keys($condition))."` = ?";
948 if ((count($command['param']) > 1) || is_int($array_key)) {
949 $sql = "DELETE FROM `".$command['table']."`".$condition_string;
950 logger(self::replace_parameters($sql, $condition), LOGGER_DATA);
952 if (!self::e($sql, $condition)) {
953 if ($do_transaction) {
959 $key_table = $command['table'];
960 $key_param = array_keys($command['param'])[0];
961 $value = array_values($command['param'])[0];
963 // Split the SQL queries in chunks of 100 values
964 // We do the $i stuff here to make the code better readable
965 $i = $counter[$key_table][$key_param];
966 if (count($compacted[$key_table][$key_param][$i]) > 100) {
970 $compacted[$key_table][$key_param][$i][$value] = $value;
971 $counter[$key_table][$key_param] = $i;
974 foreach ($compacted AS $table => $values) {
975 foreach ($values AS $field => $field_value_list) {
976 foreach ($field_value_list AS $field_values) {
977 $sql = "DELETE FROM `".$table."` WHERE `".$field."` IN (".
978 substr(str_repeat("?, ", count($field_values)), 0, -2).");";
980 logger(self::replace_parameters($sql, $field_values), LOGGER_DATA);
982 if (!self::e($sql, $field_values)) {
983 if ($do_transaction) {
991 if ($do_transaction) {
1001 * @brief Updates rows
1003 * Updates rows in the database. When $old_fields is set to an array,
1004 * the system will only do an update if the fields in that array changed.
1007 * Only the values in $old_fields are compared.
1008 * This is an intentional behaviour.
1011 * We include the timestamp field in $fields but not in $old_fields.
1012 * Then the row will only get the new timestamp when the other fields had changed.
1014 * When $old_fields is set to a boolean value the system will do this compare itself.
1015 * When $old_fields is set to "true" the system will do an insert if the row doesn't exists.
1018 * Only set $old_fields to a boolean value when you are sure that you will update a single row.
1019 * When you set $old_fields to "true" then $fields must contain all relevant fields!
1021 * @param string $table Table name
1022 * @param array $fields contains the fields that are updated
1023 * @param array $condition condition array with the key values
1024 * @param array|boolean $old_fields array with the old field values that are about to be replaced (true = update on duplicate)
1026 * @return boolean was the update successfull?
1028 public static function update($table, $fields, $condition, $old_fields = array()) {
1030 if (empty($table) || empty($fields) || empty($condition)) {
1031 logger('Table, fields and condition have to be set');
1035 $table = self::escape($table);
1037 $array_element = each($condition);
1038 $array_key = $array_element['key'];
1039 if (is_int($array_key)) {
1040 $condition_string = " WHERE ".array_shift($condition);
1042 $condition_string = " WHERE `".implode("` = ? AND `", array_keys($condition))."` = ?";
1045 if (is_bool($old_fields)) {
1046 $do_insert = $old_fields;
1048 $old_fields = self::select($table, array(), $condition, array('limit' => 1));
1050 if (is_bool($old_fields)) {
1052 $values = array_merge($condition, $fields);
1053 return self::insert($table, $values, $do_insert);
1055 $old_fields = array();
1059 $do_update = (count($old_fields) == 0);
1061 foreach ($old_fields AS $fieldname => $content) {
1062 if (isset($fields[$fieldname])) {
1063 if ($fields[$fieldname] == $content) {
1064 unset($fields[$fieldname]);
1071 if (!$do_update || (count($fields) == 0)) {
1075 $sql = "UPDATE `".$table."` SET `".
1076 implode("` = ?, `", array_keys($fields))."` = ?".$condition_string;
1078 $params1 = array_values($fields);
1079 $params2 = array_values($condition);
1080 $params = array_merge_recursive($params1, $params2);
1082 return self::e($sql, $params);
1086 * @brief Select rows from a table
1088 * @param string $table Table name
1089 * @param array $fields array of selected fields
1090 * @param array $condition array of fields for condition
1091 * @param array $params array of several parameters
1093 * @return boolean|object If "limit" is equal "1" only a single row is returned, else a query object is returned
1097 * $fields = array("id", "uri", "uid", "network");
1099 * $condition = array("uid" => 1, "network" => 'dspr');
1101 * $condition = array("`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr');
1103 * $params = array("order" => array("id", "received" => true), "limit" => 1);
1105 * $data = dba::select($table, $fields, $condition, $params);
1107 public static function select($table, array $fields = [], array $condition = [], array $params = [])
1113 if (count($fields) > 0) {
1114 $select_fields = "`".implode("`, `", array_values($fields))."`";
1116 $select_fields = "*";
1119 $condition_string = self::buildCondition($condition);
1122 $single_row = false;
1124 if (isset($params['order'])) {
1125 $param_string .= " ORDER BY ";
1126 foreach ($params['order'] AS $fields => $order) {
1127 if (!is_int($fields)) {
1128 $param_string .= "`".$fields."` ".($order ? "DESC" : "ASC").", ";
1130 $param_string .= "`".$order."`, ";
1133 $param_string = substr($param_string, 0, -2);
1136 if (isset($params['limit']) && is_int($params['limit'])) {
1137 $param_string .= " LIMIT ".$params['limit'];
1138 $single_row = ($params['limit'] == 1);
1141 if (isset($params['limit']) && is_array($params['limit'])) {
1142 $param_string .= " LIMIT ".intval($params['limit'][0]).", ".intval($params['limit'][1]);
1143 $single_row = ($params['limit'][1] == 1);
1146 if (isset($params['only_query']) && $params['only_query']) {
1147 $single_row = !$params['only_query'];
1150 $sql = "SELECT ".$select_fields." FROM `".$table."`".$condition_string.$param_string;
1152 $result = self::p($sql, $condition);
1154 if (is_bool($result) || !$single_row) {
1157 $row = self::fetch($result);
1158 self::close($result);
1164 * @brief Counts the rows from a table satisfying the provided condition
1166 * @param string $table Table name
1167 * @param array $condition array of fields for condition
1174 * $condition = ["uid" => 1, "network" => 'dspr'];
1176 * $condition = ["`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr'];
1178 * $count = dba::count($table, $condition);
1180 public static function count($table, array $condition = [])
1186 $condition_string = self::buildCondition($condition);
1188 $sql = "SELECT COUNT(*) AS `count` FROM `".$table."`".$condition_string;
1190 $row = self::fetch_first($sql, $condition);
1192 return $row['count'];
1196 * @brief Returns the SQL condition string built from the provided condition array
1198 * This function operates with two modes.
1199 * - Supplied with a filed/value associative array, it builds simple strict
1200 * equality conditions linked by AND.
1201 * - Supplied with a flat list, the first element is the condition string and
1202 * the following arguments are the values to be interpolated
1204 * $condition = ["uid" => 1, "network" => 'dspr'];
1206 * $condition = ["`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr'];
1208 * In either case, the provided array is left with the parameters only
1210 * @param array $condition
1213 private static function buildCondition(array &$condition = [])
1215 $condition_string = '';
1216 if (count($condition) > 0) {
1217 $array_element = each($condition);
1218 $array_key = $array_element['key'];
1219 if (is_int($array_key)) {
1220 $condition_string = " WHERE ".array_shift($condition);
1222 $condition_string = " WHERE `".implode("` = ? AND `", array_keys($condition))."` = ?";
1226 return $condition_string;
1230 * @brief Fills an array with data from a query
1232 * @param object $stmt statement object
1233 * @return array Data array
1235 public static function inArray($stmt, $do_close = true) {
1236 if (is_bool($stmt)) {
1241 while ($row = self::fetch($stmt)) {
1251 * @brief Returns the error number of the last query
1253 * @return string Error number (0 if no error)
1255 public static function errorNo() {
1256 return self::$errorno;
1260 * @brief Returns the error message of the last query
1262 * @return string Error message ('' if no error)
1264 public static function errorMessage() {
1265 return self::$error;
1269 * @brief Closes the current statement
1271 * @param object $stmt statement object
1272 * @return boolean was the close successfull?
1274 public static function close($stmt) {
1275 if (!is_object($stmt)) {
1279 switch (self::$driver) {
1281 return $stmt->closeCursor();
1283 $stmt->free_result();
1284 return $stmt->close();
1289 function dbesc($str) {
1290 if (dba::$connected) {
1291 return(dba::escape($str));
1293 return(str_replace("'","\\'",$str));
1298 * @brief execute SQL query with printf style args - deprecated
1300 * Please use the dba:: functions instead:
1301 * dba::select, dba::exists, dba::insert
1302 * dba::delete, dba::update, dba::p, dba::e
1304 * @param $args Query parameters (1 to N parameters of different types)
1305 * @return array Query array
1308 $args = func_get_args();
1311 if (!dba::$connected) {
1315 $sql = dba::clean_query($sql);
1316 $sql = dba::any_value_fallback($sql);
1318 $stmt = @vsprintf($sql, $args);
1320 $ret = dba::p($stmt);
1322 if (is_bool($ret)) {
1326 $columns = dba::columnCount($ret);
1328 $data = dba::inArray($ret);
1330 if ((count($data) == 0) && ($columns == 0)) {
1337 function dba_timer() {
1338 return microtime(true);