3 use Friendica\Core\L10n;
4 use Friendica\Core\System;
5 use Friendica\Database\DBM;
6 use Friendica\Database\DBStructure;
7 use Friendica\Util\DateTimeFormat;
10 * @class MySQL database class
12 * This class is for the low level database stuff that does driver specific things.
16 public static $connected = false;
18 private static $_server_info = '';
20 private static $driver;
21 private static $error = false;
22 private static $errorno = 0;
23 private static $affected_rows = 0;
24 private static $in_transaction = false;
25 private static $relation = [];
27 public static function connect($serveraddr, $user, $pass, $db, $install = false) {
28 if (!is_null(self::$db)) {
34 $stamp1 = microtime(true);
36 $serveraddr = trim($serveraddr);
38 $serverdata = explode(':', $serveraddr);
39 $server = $serverdata[0];
41 if (count($serverdata) > 1) {
42 $port = trim($serverdata[1]);
45 $server = trim($server);
50 if (!(strlen($server) && strlen($user))) {
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 = L10n::t('Cannot locate DNS info for database server \'%s\'', $server);
63 if (class_exists('\PDO') && in_array('mysql', PDO::getAvailableDrivers())) {
64 self::$driver = 'pdo';
65 $connect = "mysql:host=".$server.";dbname=".$db;
68 $connect .= ";port=".$port;
71 if (isset($a->config["system"]["db_charset"])) {
72 $connect .= ";charset=".$a->config["system"]["db_charset"];
75 self::$db = @new PDO($connect, $user, $pass);
76 self::$connected = true;
77 } catch (PDOException $e) {
81 if (!self::$connected && class_exists('mysqli')) {
82 self::$driver = 'mysqli';
83 self::$db = @new mysqli($server, $user, $pass, $db, $port);
84 if (!mysqli_connect_errno()) {
85 self::$connected = true;
87 if (isset($a->config["system"]["db_charset"])) {
88 self::$db->set_charset($a->config["system"]["db_charset"]);
93 // No suitable SQL driver was found.
94 if (!self::$connected) {
97 $a->save_timestamp($stamp1, "network");
99 return self::$connected;
103 * @brief Returns the MySQL server version string
105 * This function discriminate between the deprecated mysql API and the current
106 * object-oriented mysqli API. Example of returned string: 5.5.46-0+deb8u1
110 public static function server_info() {
111 if (self::$_server_info == '') {
112 switch (self::$driver) {
114 self::$_server_info = self::$db->getAttribute(PDO::ATTR_SERVER_VERSION);
117 self::$_server_info = self::$db->server_info;
121 return self::$_server_info;
125 * @brief Returns the selected database name
129 public static function database_name() {
130 $ret = self::p("SELECT DATABASE() AS `db`");
131 $data = self::inArray($ret);
132 return $data[0]['db'];
136 * @brief Analyze a database query and log this if some conditions are met.
138 * @param string $query The database query that will be analyzed
140 private static function logIndex($query) {
143 if (empty($a->config["system"]["db_log_index"])) {
147 // Don't explain an explain statement
148 if (strtolower(substr($query, 0, 7)) == "explain") {
152 // Only do the explain on "select", "update" and "delete"
153 if (!in_array(strtolower(substr($query, 0, 6)), ["select", "update", "delete"])) {
157 $r = self::p("EXPLAIN ".$query);
158 if (!DBM::is_result($r)) {
162 $watchlist = explode(',', $a->config["system"]["db_log_index_watch"]);
163 $blacklist = explode(',', $a->config["system"]["db_log_index_blacklist"]);
165 while ($row = dba::fetch($r)) {
166 if ((intval($a->config["system"]["db_loglimit_index"]) > 0)) {
167 $log = (in_array($row['key'], $watchlist) &&
168 ($row['rows'] >= intval($a->config["system"]["db_loglimit_index"])));
173 if ((intval($a->config["system"]["db_loglimit_index_high"]) > 0) && ($row['rows'] >= intval($a->config["system"]["db_loglimit_index_high"]))) {
177 if (in_array($row['key'], $blacklist) || ($row['key'] == "")) {
182 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
183 @file_put_contents($a->config["system"]["db_log_index"], DateTimeFormat::utcNow()."\t".
184 $row['key']."\t".$row['rows']."\t".$row['Extra']."\t".
185 basename($backtrace[1]["file"])."\t".
186 $backtrace[1]["line"]."\t".$backtrace[2]["function"]."\t".
187 substr($query, 0, 2000)."\n", FILE_APPEND);
192 public static function escape($str) {
193 switch (self::$driver) {
195 return substr(@self::$db->quote($str, PDO::PARAM_STR), 1, -1);
197 return @self::$db->real_escape_string($str);
201 public static function connected() {
204 switch (self::$driver) {
206 $r = dba::p("SELECT 1");
207 if (DBM::is_result($r)) {
208 $row = dba::inArray($r);
209 $connected = ($row[0]['1'] == '1');
213 $connected = self::$db->ping();
220 * @brief Replaces ANY_VALUE() function by MIN() function,
221 * if the database server does not support ANY_VALUE().
223 * Considerations for Standard SQL, or MySQL with ONLY_FULL_GROUP_BY (default since 5.7.5).
224 * ANY_VALUE() is available from MySQL 5.7.5 https://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html
225 * A standard fall-back is to use MIN().
227 * @param string $sql An SQL string without the values
228 * @return string The input SQL string modified if necessary.
230 public static function any_value_fallback($sql) {
231 $server_info = self::server_info();
232 if (version_compare($server_info, '5.7.5', '<') ||
233 (stripos($server_info, 'MariaDB') !== false)) {
234 $sql = str_ireplace('ANY_VALUE(', 'MIN(', $sql);
240 * @brief beautifies the query - useful for "SHOW PROCESSLIST"
242 * This is safe when we bind the parameters later.
243 * The parameter values aren't part of the SQL.
245 * @param string $sql An SQL string without the values
246 * @return string The input SQL string modified if necessary.
248 public static function clean_query($sql) {
249 $search = ["\t", "\n", "\r", " "];
250 $replace = [' ', ' ', ' ', ' '];
253 $sql = str_replace($search, $replace, $sql);
254 } while ($oldsql != $sql);
261 * @brief Replaces the ? placeholders with the parameters in the $args array
263 * @param string $sql SQL query
264 * @param array $args The parameters that are to replace the ? placeholders
265 * @return string The replaced SQL query
267 private static function replaceParameters($sql, $args) {
269 foreach ($args AS $param => $value) {
270 if (is_int($args[$param]) || is_float($args[$param])) {
271 $replace = intval($args[$param]);
273 $replace = "'".self::escape($args[$param])."'";
276 $pos = strpos($sql, '?', $offset);
277 if ($pos !== false) {
278 $sql = substr_replace($sql, $replace, $pos, 1);
280 $offset = $pos + strlen($replace);
286 * @brief Convert parameter array to an universal form
287 * @param array $args Parameter array
288 * @return array universalized parameter array
290 private static function getParam($args) {
293 // When the second function parameter is an array then use this as the parameter array
294 if ((count($args) > 0) && (is_array($args[1]))) {
302 * @brief Executes a prepared statement that returns data
303 * @usage Example: $r = p("SELECT * FROM `item` WHERE `guid` = ?", $guid);
305 * Please only use it with complicated queries.
306 * For all regular queries please use dba::select or dba::exists
308 * @param string $sql SQL statement
309 * @return bool|object statement object
311 public static function p($sql) {
314 $stamp1 = microtime(true);
316 $params = self::getParam(func_get_args());
318 // Renumber the array keys to be sure that they fit
321 foreach ($params AS $param) {
322 // Avoid problems with some MySQL servers and boolean values. See issue #3645
323 if (is_bool($param)) {
324 $param = (int)$param;
326 $args[++$i] = $param;
329 if (!self::$connected) {
333 if ((substr_count($sql, '?') != count($args)) && (count($args) > 0)) {
334 // Question: Should we continue or stop the query here?
335 logger('Parameter mismatch. Query "'.$sql.'" - Parameters '.print_r($args, true), LOGGER_DEBUG);
338 $sql = self::clean_query($sql);
339 $sql = self::any_value_fallback($sql);
343 if (x($a->config,'system') && x($a->config['system'], 'db_callstack')) {
344 $sql = "/*".System::callstack()." */ ".$sql;
349 self::$affected_rows = 0;
351 // We have to make some things different if this function is called from "e"
352 $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2);
354 if (isset($trace[1])) {
355 $called_from = $trace[1];
357 // We use just something that is defined to avoid warnings
358 $called_from = $trace[0];
360 // We are having an own error logging in the function "e"
361 $called_from_e = ($called_from['function'] == 'e');
363 switch (self::$driver) {
365 // If there are no arguments we use "query"
366 if (count($args) == 0) {
367 if (!$retval = self::$db->query($sql)) {
368 $errorInfo = self::$db->errorInfo();
369 self::$error = $errorInfo[2];
370 self::$errorno = $errorInfo[1];
374 self::$affected_rows = $retval->rowCount();
378 if (!$stmt = self::$db->prepare($sql)) {
379 $errorInfo = self::$db->errorInfo();
380 self::$error = $errorInfo[2];
381 self::$errorno = $errorInfo[1];
386 foreach ($args AS $param => $value) {
387 $stmt->bindParam($param, $args[$param]);
390 if (!$stmt->execute()) {
391 $errorInfo = $stmt->errorInfo();
392 self::$error = $errorInfo[2];
393 self::$errorno = $errorInfo[1];
397 self::$affected_rows = $retval->rowCount();
401 // There are SQL statements that cannot be executed with a prepared statement
402 $parts = explode(' ', $orig_sql);
403 $command = strtolower($parts[0]);
404 $can_be_prepared = in_array($command, ['select', 'update', 'insert', 'delete']);
406 // The fallback routine is called as well when there are no arguments
407 if (!$can_be_prepared || (count($args) == 0)) {
408 $retval = self::$db->query(self::replaceParameters($sql, $args));
409 if (self::$db->errno) {
410 self::$error = self::$db->error;
411 self::$errorno = self::$db->errno;
414 if (isset($retval->num_rows)) {
415 self::$affected_rows = $retval->num_rows;
417 self::$affected_rows = self::$db->affected_rows;
423 $stmt = self::$db->stmt_init();
425 if (!$stmt->prepare($sql)) {
426 self::$error = $stmt->error;
427 self::$errorno = $stmt->errno;
434 foreach ($args AS $param => $value) {
435 if (is_int($args[$param])) {
437 } elseif (is_float($args[$param])) {
439 } elseif (is_string($args[$param])) {
444 $values[] = &$args[$param];
447 if (count($values) > 0) {
448 array_unshift($values, $params);
449 call_user_func_array([$stmt, 'bind_param'], $values);
452 if (!$stmt->execute()) {
453 self::$error = self::$db->error;
454 self::$errorno = self::$db->errno;
457 $stmt->store_result();
459 self::$affected_rows = $retval->affected_rows;
464 // We are having an own error logging in the function "e"
465 if ((self::$errorno != 0) && !$called_from_e) {
466 // We have to preserve the error code, somewhere in the logging it get lost
467 $error = self::$error;
468 $errorno = self::$errorno;
470 logger('DB Error '.self::$errorno.': '.self::$error."\n".
471 System::callstack(8)."\n".self::replaceParameters($sql, $params));
473 self::$error = $error;
474 self::$errorno = $errorno;
477 $a->save_timestamp($stamp1, 'database');
479 if (x($a->config,'system') && x($a->config['system'], 'db_log')) {
481 $stamp2 = microtime(true);
482 $duration = (float)($stamp2 - $stamp1);
484 if (($duration > $a->config["system"]["db_loglimit"])) {
485 $duration = round($duration, 3);
486 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
488 @file_put_contents($a->config["system"]["db_log"], DateTimeFormat::utcNow()."\t".$duration."\t".
489 basename($backtrace[1]["file"])."\t".
490 $backtrace[1]["line"]."\t".$backtrace[2]["function"]."\t".
491 substr(self::replaceParameters($sql, $args), 0, 2000)."\n", FILE_APPEND);
498 * @brief Executes a prepared statement like UPDATE or INSERT that doesn't return data
500 * Please use dba::delete, dba::insert, dba::update, ... instead
502 * @param string $sql SQL statement
503 * @return boolean Was the query successfull? False is returned only if an error occurred
505 public static function e($sql) {
508 $stamp = microtime(true);
510 $params = self::getParam(func_get_args());
512 // In a case of a deadlock we are repeating the query 20 times
516 $stmt = self::p($sql, $params);
518 if (is_bool($stmt)) {
520 } elseif (is_object($stmt)) {
528 } while ((self::$errorno == 1213) && (--$timeout > 0));
530 if (self::$errorno != 0) {
531 // We have to preserve the error code, somewhere in the logging it get lost
532 $error = self::$error;
533 $errorno = self::$errorno;
535 logger('DB Error '.self::$errorno.': '.self::$error."\n".
536 System::callstack(8)."\n".self::replaceParameters($sql, $params));
538 self::$error = $error;
539 self::$errorno = $errorno;
542 $a->save_timestamp($stamp, "database_write");
548 * @brief Check if data exists
550 * @param string $table Table name
551 * @param array $condition array of fields for condition
553 * @return boolean Are there rows for that condition?
555 public static function exists($table, $condition) {
563 $first_key = key($condition);
564 if (!is_int($first_key)) {
565 $fields = [$first_key];
568 $stmt = self::select($table, $fields, $condition, ['limit' => 1]);
570 if (is_bool($stmt)) {
573 $retval = (self::num_rows($stmt) > 0);
582 * Fetches the first row
584 * Please use dba::selectFirst or dba::exists whenever this is possible.
586 * @brief Fetches the first row
587 * @param string $sql SQL statement
588 * @return array first row of query
590 public static function fetch_first($sql) {
591 $params = self::getParam(func_get_args());
593 $stmt = self::p($sql, $params);
595 if (is_bool($stmt)) {
598 $retval = self::fetch($stmt);
607 * @brief Returns the number of affected rows of the last statement
609 * @return int Number of rows
611 public static function affected_rows() {
612 return self::$affected_rows;
616 * @brief Returns the number of columns of a statement
618 * @param object Statement object
619 * @return int Number of columns
621 public static function columnCount($stmt) {
622 if (!is_object($stmt)) {
625 switch (self::$driver) {
627 return $stmt->columnCount();
629 return $stmt->field_count;
634 * @brief Returns the number of rows of a statement
636 * @param PDOStatement|mysqli_result|mysqli_stmt Statement object
637 * @return int Number of rows
639 public static function num_rows($stmt) {
640 if (!is_object($stmt)) {
643 switch (self::$driver) {
645 return $stmt->rowCount();
647 return $stmt->num_rows;
653 * @brief Fetch a single row
655 * @param mixed $stmt statement object
656 * @return array current row
658 public static function fetch($stmt) {
661 $stamp1 = microtime(true);
665 if (!is_object($stmt)) {
669 switch (self::$driver) {
671 $columns = $stmt->fetch(PDO::FETCH_ASSOC);
674 if (get_class($stmt) == 'mysqli_result') {
675 $columns = $stmt->fetch_assoc();
679 // This code works, but is slow
681 // Bind the result to a result array
685 for ($x = 0; $x < $stmt->field_count; $x++) {
686 $cols[] = &$cols_num[$x];
689 call_user_func_array([$stmt, 'bind_result'], $cols);
691 if (!$stmt->fetch()) {
696 // We need to get the field names for the array keys
697 // It seems that there is no better way to do this.
698 $result = $stmt->result_metadata();
699 $fields = $result->fetch_fields();
701 foreach ($cols_num AS $param => $col) {
702 $columns[$fields[$param]->name] = $col;
706 $a->save_timestamp($stamp1, 'database');
712 * @brief Insert a row into a table
714 * @param string $table Table name
715 * @param array $param parameter array
716 * @param bool $on_duplicate_update Do an update on a duplicate entry
718 * @return boolean was the insert successfull?
720 public static function insert($table, $param, $on_duplicate_update = false) {
722 if (empty($table) || empty($param)) {
723 logger('Table and fields have to be set');
727 $sql = "INSERT INTO `".self::escape($table)."` (`".implode("`, `", array_keys($param))."`) VALUES (".
728 substr(str_repeat("?, ", count($param)), 0, -2).")";
730 if ($on_duplicate_update) {
731 $sql .= " ON DUPLICATE KEY UPDATE `".implode("` = ?, `", array_keys($param))."` = ?";
733 $values = array_values($param);
734 $param = array_merge_recursive($values, $values);
737 return self::e($sql, $param);
741 * @brief Fetch the id of the last insert command
743 * @return integer Last inserted id
745 public static function lastInsertId() {
746 switch (self::$driver) {
748 $id = self::$db->lastInsertId();
751 $id = self::$db->insert_id;
758 * @brief Locks a table for exclusive write access
760 * This function can be extended in the future to accept a table array as well.
762 * @param string $table Table name
764 * @return boolean was the lock successful?
766 public static function lock($table) {
767 // See here: https://dev.mysql.com/doc/refman/5.7/en/lock-tables-and-transactions.html
768 self::e("SET autocommit=0");
769 $success = self::e("LOCK TABLES `".self::escape($table)."` WRITE");
771 self::e("SET autocommit=1");
773 self::$in_transaction = true;
779 * @brief Unlocks all locked tables
781 * @return boolean was the unlock successful?
783 public static function unlock() {
784 // See here: https://dev.mysql.com/doc/refman/5.7/en/lock-tables-and-transactions.html
786 $success = self::e("UNLOCK TABLES");
787 self::e("SET autocommit=1");
788 self::$in_transaction = false;
793 * @brief Starts a transaction
795 * @return boolean Was the command executed successfully?
797 public static function transaction() {
798 if (!self::e('COMMIT')) {
801 if (!self::e('START TRANSACTION')) {
804 self::$in_transaction = true;
809 * @brief Does a commit
811 * @return boolean Was the command executed successfully?
813 public static function commit() {
814 if (!self::e('COMMIT')) {
817 self::$in_transaction = false;
822 * @brief Does a rollback
824 * @return boolean Was the command executed successfully?
826 public static function rollback() {
827 if (!self::e('ROLLBACK')) {
830 self::$in_transaction = false;
835 * @brief Build the array with the table relations
837 * The array is build from the database definitions in DBStructure.php
839 * This process must only be started once, since the value is cached.
841 private static function buildRelationData() {
842 $definition = DBStructure::definition();
844 foreach ($definition AS $table => $structure) {
845 foreach ($structure['fields'] AS $field => $field_struct) {
846 if (isset($field_struct['relation'])) {
847 foreach ($field_struct['relation'] AS $rel_table => $rel_field) {
848 self::$relation[$rel_table][$rel_field][$table][] = $field;
856 * @brief Delete a row from a table
858 * @param string $table Table name
859 * @param array $conditions Field condition(s)
860 * @param boolean $in_process Internal use: Only do a commit after the last delete
861 * @param array $callstack Internal use: prevent endless loops
863 * @return boolean|array was the delete successful? When $in_process is set: deletion data
865 public static function delete($table, array $conditions, $in_process = false, array &$callstack = [])
867 if (empty($table) || empty($conditions)) {
868 logger('Table and conditions have to be set');
874 // Create a key for the loop prevention
875 $key = $table . ':' . implode(':', array_keys($conditions)) . ':' . implode(':', $conditions);
877 // We quit when this key already exists in the callstack.
878 if (isset($callstack[$key])) {
882 $callstack[$key] = true;
884 $table = self::escape($table);
886 $commands[$key] = ['table' => $table, 'conditions' => $conditions];
888 // To speed up the whole process we cache the table relations
889 if (count(self::$relation) == 0) {
890 self::buildRelationData();
893 // Is there a relation entry for the table?
894 if (isset(self::$relation[$table])) {
895 // We only allow a simple "one field" relation.
896 $field = array_keys(self::$relation[$table])[0];
897 $rel_def = array_values(self::$relation[$table])[0];
899 // Create a key for preventing double queries
900 $qkey = $field . '-' . $table . ':' . implode(':', array_keys($conditions)) . ':' . implode(':', $conditions);
902 // When the search field is the relation field, we don't need to fetch the rows
903 // This is useful when the leading record is already deleted in the frontend but the rest is done in the backend
904 if ((count($conditions) == 1) && ($field == array_keys($conditions)[0])) {
905 foreach ($rel_def AS $rel_table => $rel_fields) {
906 foreach ($rel_fields AS $rel_field) {
907 $retval = self::delete($rel_table, [$rel_field => array_values($conditions)[0]], true, $callstack);
908 $commands = array_merge($commands, $retval);
911 // We quit when this key already exists in the callstack.
912 } elseif (!isset($callstack[$qkey])) {
914 $callstack[$qkey] = true;
916 // Fetch all rows that are to be deleted
917 $data = self::select($table, [$field], $conditions);
919 while ($row = self::fetch($data)) {
920 // Now we accumulate the delete commands
921 $retval = self::delete($table, [$field => $row[$field]], true, $callstack);
922 $commands = array_merge($commands, $retval);
927 // Since we had split the delete command we don't need the original command anymore
928 unset($commands[$key]);
933 // Now we finalize the process
934 $do_transaction = !self::$in_transaction;
936 if ($do_transaction) {
943 foreach ($commands AS $command) {
944 $conditions = $command['conditions'];
946 $first_key = key($conditions);
948 $condition_string = self::buildCondition($conditions);
950 if ((count($command['conditions']) > 1) || is_int($first_key)) {
951 $sql = "DELETE FROM `" . $command['table'] . "`" . $condition_string;
952 logger(self::replaceParameters($sql, $conditions), LOGGER_DATA);
954 if (!self::e($sql, $conditions)) {
955 if ($do_transaction) {
961 $key_table = $command['table'];
962 $key_condition = array_keys($command['conditions'])[0];
963 $value = array_values($command['conditions'])[0];
965 // Split the SQL queries in chunks of 100 values
966 // We do the $i stuff here to make the code better readable
967 $i = $counter[$key_table][$key_condition];
968 if (count($compacted[$key_table][$key_condition][$i]) > 100) {
972 $compacted[$key_table][$key_condition][$i][$value] = $value;
973 $counter[$key_table][$key_condition] = $i;
976 foreach ($compacted AS $table => $values) {
977 foreach ($values AS $field => $field_value_list) {
978 foreach ($field_value_list AS $field_values) {
979 $sql = "DELETE FROM `" . $table . "` WHERE `" . $field . "` IN (" .
980 substr(str_repeat("?, ", count($field_values)), 0, -2) . ");";
982 logger(self::replaceParameters($sql, $field_values), LOGGER_DATA);
984 if (!self::e($sql, $field_values)) {
985 if ($do_transaction) {
993 if ($do_transaction) {
1003 * @brief Updates rows
1005 * Updates rows in the database. When $old_fields is set to an array,
1006 * the system will only do an update if the fields in that array changed.
1009 * Only the values in $old_fields are compared.
1010 * This is an intentional behaviour.
1013 * We include the timestamp field in $fields but not in $old_fields.
1014 * Then the row will only get the new timestamp when the other fields had changed.
1016 * When $old_fields is set to a boolean value the system will do this compare itself.
1017 * When $old_fields is set to "true" the system will do an insert if the row doesn't exists.
1020 * Only set $old_fields to a boolean value when you are sure that you will update a single row.
1021 * When you set $old_fields to "true" then $fields must contain all relevant fields!
1023 * @param string $table Table name
1024 * @param array $fields contains the fields that are updated
1025 * @param array $condition condition array with the key values
1026 * @param array|boolean $old_fields array with the old field values that are about to be replaced (true = update on duplicate)
1028 * @return boolean was the update successfull?
1030 public static function update($table, $fields, $condition, $old_fields = []) {
1032 if (empty($table) || empty($fields) || empty($condition)) {
1033 logger('Table, fields and condition have to be set');
1037 $table = self::escape($table);
1039 $condition_string = self::buildCondition($condition);
1041 if (is_bool($old_fields)) {
1042 $do_insert = $old_fields;
1044 $old_fields = self::selectFirst($table, [], $condition);
1046 if (is_bool($old_fields)) {
1048 $values = array_merge($condition, $fields);
1049 return self::insert($table, $values, $do_insert);
1055 $do_update = (count($old_fields) == 0);
1057 foreach ($old_fields AS $fieldname => $content) {
1058 if (isset($fields[$fieldname])) {
1059 if ($fields[$fieldname] == $content) {
1060 unset($fields[$fieldname]);
1067 if (!$do_update || (count($fields) == 0)) {
1071 $sql = "UPDATE `".$table."` SET `".
1072 implode("` = ?, `", array_keys($fields))."` = ?".$condition_string;
1074 $params1 = array_values($fields);
1075 $params2 = array_values($condition);
1076 $params = array_merge_recursive($params1, $params2);
1078 return self::e($sql, $params);
1082 * Retrieve a single record from a table and returns it in an associative array
1084 * @brief Retrieve a single record from a table
1085 * @param string $table
1086 * @param array $fields
1087 * @param array $condition
1088 * @param array $params
1089 * @return bool|array
1092 public static function selectFirst($table, array $fields = [], array $condition = [], $params = [])
1094 $params['limit'] = 1;
1095 $result = self::select($table, $fields, $condition, $params);
1097 if (is_bool($result)) {
1100 $row = self::fetch($result);
1101 self::close($result);
1107 * @brief Select rows from a table
1109 * @param string $table Table name
1110 * @param array $fields Array of selected fields, empty for all
1111 * @param array $condition Array of fields for condition
1112 * @param array $params Array of several parameters
1114 * @return boolean|object
1118 * $fields = array("id", "uri", "uid", "network");
1120 * $condition = array("uid" => 1, "network" => 'dspr');
1122 * $condition = array("`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr');
1124 * $params = array("order" => array("id", "received" => true), "limit" => 10);
1126 * $data = dba::select($table, $fields, $condition, $params);
1128 public static function select($table, array $fields = [], array $condition = [], array $params = [])
1134 $table = self::escape($table);
1136 if (count($fields) > 0) {
1137 $select_fields = "`" . implode("`, `", array_values($fields)) . "`";
1139 $select_fields = "*";
1142 $condition_string = self::buildCondition($condition);
1145 if (isset($params['order'])) {
1146 $order_string = " ORDER BY ";
1147 foreach ($params['order'] AS $fields => $order) {
1148 if (!is_int($fields)) {
1149 $order_string .= "`" . $fields . "` " . ($order ? "DESC" : "ASC") . ", ";
1151 $order_string .= "`" . $order . "`, ";
1154 $order_string = substr($order_string, 0, -2);
1158 if (isset($params['limit']) && is_int($params['limit'])) {
1159 $limit_string = " LIMIT " . $params['limit'];
1162 if (isset($params['limit']) && is_array($params['limit'])) {
1163 $limit_string = " LIMIT " . intval($params['limit'][0]) . ", " . intval($params['limit'][1]);
1166 $sql = "SELECT " . $select_fields . " FROM `" . $table . "`" . $condition_string . $order_string . $limit_string;
1168 $result = self::p($sql, $condition);
1174 * @brief Counts the rows from a table satisfying the provided condition
1176 * @param string $table Table name
1177 * @param array $condition array of fields for condition
1184 * $condition = ["uid" => 1, "network" => 'dspr'];
1186 * $condition = ["`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr'];
1188 * $count = dba::count($table, $condition);
1190 public static function count($table, array $condition = [])
1196 $condition_string = self::buildCondition($condition);
1198 $sql = "SELECT COUNT(*) AS `count` FROM `".$table."`".$condition_string;
1200 $row = self::fetch_first($sql, $condition);
1202 return $row['count'];
1206 * @brief Returns the SQL condition string built from the provided condition array
1208 * This function operates with two modes.
1209 * - Supplied with a filed/value associative array, it builds simple strict
1210 * equality conditions linked by AND.
1211 * - Supplied with a flat list, the first element is the condition string and
1212 * the following arguments are the values to be interpolated
1214 * $condition = ["uid" => 1, "network" => 'dspr'];
1216 * $condition = ["`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr'];
1218 * In either case, the provided array is left with the parameters only
1220 * @param array $condition
1223 private static function buildCondition(array &$condition = [])
1225 $condition_string = '';
1226 if (count($condition) > 0) {
1228 $first_key = key($condition);
1229 if (is_int($first_key)) {
1230 $condition_string = " WHERE ".array_shift($condition);
1233 $condition_string = "";
1234 foreach ($condition as $field => $value) {
1235 if ($condition_string != "") {
1236 $condition_string .= " AND ";
1238 if (is_array($value)) {
1239 $new_values = array_merge($new_values, array_values($value));
1240 $placeholders = substr(str_repeat("?, ", count($value)), 0, -2);
1241 $condition_string .= "`" . $field . "` IN (" . $placeholders . ")";
1243 $new_values[$field] = $value;
1244 $condition_string .= "`" . $field . "` = ?";
1247 $condition_string = " WHERE " . $condition_string;
1248 $condition = $new_values;
1252 return $condition_string;
1256 * @brief Fills an array with data from a query
1258 * @param object $stmt statement object
1259 * @return array Data array
1261 public static function inArray($stmt, $do_close = true) {
1262 if (is_bool($stmt)) {
1267 while ($row = self::fetch($stmt)) {
1277 * @brief Returns the error number of the last query
1279 * @return string Error number (0 if no error)
1281 public static function errorNo() {
1282 return self::$errorno;
1286 * @brief Returns the error message of the last query
1288 * @return string Error message ('' if no error)
1290 public static function errorMessage() {
1291 return self::$error;
1295 * @brief Closes the current statement
1297 * @param object $stmt statement object
1298 * @return boolean was the close successful?
1300 public static function close($stmt) {
1303 $stamp1 = microtime(true);
1305 if (!is_object($stmt)) {
1309 switch (self::$driver) {
1311 $ret = $stmt->closeCursor();
1314 $stmt->free_result();
1315 $ret = $stmt->close();
1319 $a->save_timestamp($stamp1, 'database');
1325 function dbesc($str) {
1326 if (dba::$connected) {
1327 return(dba::escape($str));
1329 return(str_replace("'","\\'",$str));
1334 * @brief execute SQL query with printf style args - deprecated
1336 * Please use the dba:: functions instead:
1337 * dba::select, dba::exists, dba::insert
1338 * dba::delete, dba::update, dba::p, dba::e
1340 * @param $args Query parameters (1 to N parameters of different types)
1341 * @return array|bool Query array
1344 $args = func_get_args();
1347 if (!dba::$connected) {
1351 $sql = dba::clean_query($sql);
1352 $sql = dba::any_value_fallback($sql);
1354 $stmt = @vsprintf($sql, $args);
1356 $ret = dba::p($stmt);
1358 if (is_bool($ret)) {
1362 $columns = dba::columnCount($ret);
1364 $data = dba::inArray($ret);
1366 if ((count($data) == 0) && ($columns == 0)) {
1373 function dba_timer() {
1374 return microtime(true);