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 = true;
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))) {
51 self::$connected = false;
57 if (strlen($server) && ($server !== 'localhost') && ($server !== '127.0.0.1')) {
58 if (! dns_get_record($server, DNS_A + DNS_CNAME + DNS_PTR)) {
59 self::$error = L10n::t('Cannot locate DNS info for database server \'%s\'', $server);
60 self::$connected = false;
67 if (class_exists('\PDO') && in_array('mysql', PDO::getAvailableDrivers())) {
68 self::$driver = 'pdo';
69 $connect = "mysql:host=".$server.";dbname=".$db;
72 $connect .= ";port=".$port;
75 if (isset($a->config["system"]["db_charset"])) {
76 $connect .= ";charset=".$a->config["system"]["db_charset"];
79 self::$db = @new PDO($connect, $user, $pass);
80 self::$connected = true;
81 } catch (PDOException $e) {
82 self::$connected = false;
86 if (!self::$connected && class_exists('mysqli')) {
87 self::$driver = 'mysqli';
88 self::$db = @new mysqli($server, $user, $pass, $db, $port);
89 if (!mysqli_connect_errno()) {
90 self::$connected = true;
92 if (isset($a->config["system"]["db_charset"])) {
93 self::$db->set_charset($a->config["system"]["db_charset"]);
98 // No suitable SQL driver was found.
99 if (!self::$connected) {
102 System::unavailable();
105 $a->save_timestamp($stamp1, "network");
111 * @brief Returns the MySQL server version string
113 * This function discriminate between the deprecated mysql API and the current
114 * object-oriented mysqli API. Example of returned string: 5.5.46-0+deb8u1
118 public static function server_info() {
119 if (self::$_server_info == '') {
120 switch (self::$driver) {
122 self::$_server_info = self::$db->getAttribute(PDO::ATTR_SERVER_VERSION);
125 self::$_server_info = self::$db->server_info;
129 return self::$_server_info;
133 * @brief Returns the selected database name
137 public static function database_name() {
138 $ret = self::p("SELECT DATABASE() AS `db`");
139 $data = self::inArray($ret);
140 return $data[0]['db'];
144 * @brief Analyze a database query and log this if some conditions are met.
146 * @param string $query The database query that will be analyzed
148 private static function log_index($query) {
151 if (empty($a->config["system"]["db_log_index"])) {
155 // Don't explain an explain statement
156 if (strtolower(substr($query, 0, 7)) == "explain") {
160 // Only do the explain on "select", "update" and "delete"
161 if (!in_array(strtolower(substr($query, 0, 6)), ["select", "update", "delete"])) {
165 $r = self::p("EXPLAIN ".$query);
166 if (!DBM::is_result($r)) {
170 $watchlist = explode(',', $a->config["system"]["db_log_index_watch"]);
171 $blacklist = explode(',', $a->config["system"]["db_log_index_blacklist"]);
173 while ($row = dba::fetch($r)) {
174 if ((intval($a->config["system"]["db_loglimit_index"]) > 0)) {
175 $log = (in_array($row['key'], $watchlist) &&
176 ($row['rows'] >= intval($a->config["system"]["db_loglimit_index"])));
181 if ((intval($a->config["system"]["db_loglimit_index_high"]) > 0) && ($row['rows'] >= intval($a->config["system"]["db_loglimit_index_high"]))) {
185 if (in_array($row['key'], $blacklist) || ($row['key'] == "")) {
190 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
191 @file_put_contents($a->config["system"]["db_log_index"], DateTimeFormat::utcNow()."\t".
192 $row['key']."\t".$row['rows']."\t".$row['Extra']."\t".
193 basename($backtrace[1]["file"])."\t".
194 $backtrace[1]["line"]."\t".$backtrace[2]["function"]."\t".
195 substr($query, 0, 2000)."\n", FILE_APPEND);
200 public static function escape($str) {
201 switch (self::$driver) {
203 return substr(@self::$db->quote($str, PDO::PARAM_STR), 1, -1);
205 return @self::$db->real_escape_string($str);
209 public static function connected() {
212 switch (self::$driver) {
214 $r = dba::p("SELECT 1");
215 if (DBM::is_result($r)) {
216 $row = dba::inArray($r);
217 $connected = ($row[0]['1'] == '1');
221 $connected = self::$db->ping();
228 * @brief Replaces ANY_VALUE() function by MIN() function,
229 * if the database server does not support ANY_VALUE().
231 * Considerations for Standard SQL, or MySQL with ONLY_FULL_GROUP_BY (default since 5.7.5).
232 * ANY_VALUE() is available from MySQL 5.7.5 https://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html
233 * A standard fall-back is to use MIN().
235 * @param string $sql An SQL string without the values
236 * @return string The input SQL string modified if necessary.
238 public static function any_value_fallback($sql) {
239 $server_info = self::server_info();
240 if (version_compare($server_info, '5.7.5', '<') ||
241 (stripos($server_info, 'MariaDB') !== false)) {
242 $sql = str_ireplace('ANY_VALUE(', 'MIN(', $sql);
248 * @brief beautifies the query - useful for "SHOW PROCESSLIST"
250 * This is safe when we bind the parameters later.
251 * The parameter values aren't part of the SQL.
253 * @param string $sql An SQL string without the values
254 * @return string The input SQL string modified if necessary.
256 public static function clean_query($sql) {
257 $search = ["\t", "\n", "\r", " "];
258 $replace = [' ', ' ', ' ', ' '];
261 $sql = str_replace($search, $replace, $sql);
262 } while ($oldsql != $sql);
269 * @brief Replaces the ? placeholders with the parameters in the $args array
271 * @param string $sql SQL query
272 * @param array $args The parameters that are to replace the ? placeholders
273 * @return string The replaced SQL query
275 private static function replace_parameters($sql, $args) {
277 foreach ($args AS $param => $value) {
278 if (is_int($args[$param]) || is_float($args[$param])) {
279 $replace = intval($args[$param]);
281 $replace = "'".self::escape($args[$param])."'";
284 $pos = strpos($sql, '?', $offset);
285 if ($pos !== false) {
286 $sql = substr_replace($sql, $replace, $pos, 1);
288 $offset = $pos + strlen($replace);
294 * @brief Convert parameter array to an universal form
295 * @param array $args Parameter array
296 * @return array universalized parameter array
298 private static function getParam($args) {
301 // When the second function parameter is an array then use this as the parameter array
302 if ((count($args) > 0) && (is_array($args[1]))) {
310 * @brief Executes a prepared statement that returns data
311 * @usage Example: $r = p("SELECT * FROM `item` WHERE `guid` = ?", $guid);
313 * Please only use it with complicated queries.
314 * For all regular queries please use dba::select or dba::exists
316 * @param string $sql SQL statement
317 * @return bool|object statement object
319 public static function p($sql) {
322 $stamp1 = microtime(true);
324 $params = self::getParam(func_get_args());
326 // Renumber the array keys to be sure that they fit
329 foreach ($params AS $param) {
330 // Avoid problems with some MySQL servers and boolean values. See issue #3645
331 if (is_bool($param)) {
332 $param = (int)$param;
334 $args[++$i] = $param;
337 if (!self::$connected) {
341 if ((substr_count($sql, '?') != count($args)) && (count($args) > 0)) {
342 // Question: Should we continue or stop the query here?
343 logger('Parameter mismatch. Query "'.$sql.'" - Parameters '.print_r($args, true), LOGGER_DEBUG);
346 $sql = self::clean_query($sql);
347 $sql = self::any_value_fallback($sql);
351 if (x($a->config,'system') && x($a->config['system'], 'db_callstack')) {
352 $sql = "/*".System::callstack()." */ ".$sql;
357 self::$affected_rows = 0;
359 // We have to make some things different if this function is called from "e"
360 $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2);
362 if (isset($trace[1])) {
363 $called_from = $trace[1];
365 // We use just something that is defined to avoid warnings
366 $called_from = $trace[0];
368 // We are having an own error logging in the function "e"
369 $called_from_e = ($called_from['function'] == 'e');
371 switch (self::$driver) {
373 // If there are no arguments we use "query"
374 if (count($args) == 0) {
375 if (!$retval = self::$db->query($sql)) {
376 $errorInfo = self::$db->errorInfo();
377 self::$error = $errorInfo[2];
378 self::$errorno = $errorInfo[1];
382 self::$affected_rows = $retval->rowCount();
386 if (!$stmt = self::$db->prepare($sql)) {
387 $errorInfo = self::$db->errorInfo();
388 self::$error = $errorInfo[2];
389 self::$errorno = $errorInfo[1];
394 foreach ($args AS $param => $value) {
395 $stmt->bindParam($param, $args[$param]);
398 if (!$stmt->execute()) {
399 $errorInfo = $stmt->errorInfo();
400 self::$error = $errorInfo[2];
401 self::$errorno = $errorInfo[1];
405 self::$affected_rows = $retval->rowCount();
409 // There are SQL statements that cannot be executed with a prepared statement
410 $parts = explode(' ', $orig_sql);
411 $command = strtolower($parts[0]);
412 $can_be_prepared = in_array($command, ['select', 'update', 'insert', 'delete']);
414 // The fallback routine is called as well when there are no arguments
415 if (!$can_be_prepared || (count($args) == 0)) {
416 $retval = self::$db->query(self::replace_parameters($sql, $args));
417 if (self::$db->errno) {
418 self::$error = self::$db->error;
419 self::$errorno = self::$db->errno;
422 if (isset($retval->num_rows)) {
423 self::$affected_rows = $retval->num_rows;
425 self::$affected_rows = self::$db->affected_rows;
431 $stmt = self::$db->stmt_init();
433 if (!$stmt->prepare($sql)) {
434 self::$error = $stmt->error;
435 self::$errorno = $stmt->errno;
442 foreach ($args AS $param => $value) {
443 if (is_int($args[$param])) {
445 } elseif (is_float($args[$param])) {
447 } elseif (is_string($args[$param])) {
452 $values[] = &$args[$param];
455 if (count($values) > 0) {
456 array_unshift($values, $params);
457 call_user_func_array([$stmt, 'bind_param'], $values);
460 if (!$stmt->execute()) {
461 self::$error = self::$db->error;
462 self::$errorno = self::$db->errno;
465 $stmt->store_result();
467 self::$affected_rows = $retval->affected_rows;
472 // We are having an own error logging in the function "e"
473 if ((self::$errorno != 0) && !$called_from_e) {
474 // We have to preserve the error code, somewhere in the logging it get lost
475 $error = self::$error;
476 $errorno = self::$errorno;
478 logger('DB Error '.self::$errorno.': '.self::$error."\n".
479 System::callstack(8)."\n".self::replace_parameters($sql, $params));
481 self::$error = $error;
482 self::$errorno = $errorno;
485 $a->save_timestamp($stamp1, 'database');
487 if (x($a->config,'system') && x($a->config['system'], 'db_log')) {
489 $stamp2 = microtime(true);
490 $duration = (float)($stamp2 - $stamp1);
492 if (($duration > $a->config["system"]["db_loglimit"])) {
493 $duration = round($duration, 3);
494 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
496 @file_put_contents($a->config["system"]["db_log"], DateTimeFormat::utcNow()."\t".$duration."\t".
497 basename($backtrace[1]["file"])."\t".
498 $backtrace[1]["line"]."\t".$backtrace[2]["function"]."\t".
499 substr(self::replace_parameters($sql, $args), 0, 2000)."\n", FILE_APPEND);
506 * @brief Executes a prepared statement like UPDATE or INSERT that doesn't return data
508 * Please use dba::delete, dba::insert, dba::update, ... instead
510 * @param string $sql SQL statement
511 * @return boolean Was the query successfull? False is returned only if an error occurred
513 public static function e($sql) {
516 $stamp = microtime(true);
518 $params = self::getParam(func_get_args());
520 // In a case of a deadlock we are repeating the query 20 times
524 $stmt = self::p($sql, $params);
526 if (is_bool($stmt)) {
528 } elseif (is_object($stmt)) {
536 } while ((self::$errorno == 1213) && (--$timeout > 0));
538 if (self::$errorno != 0) {
539 // We have to preserve the error code, somewhere in the logging it get lost
540 $error = self::$error;
541 $errorno = self::$errorno;
543 logger('DB Error '.self::$errorno.': '.self::$error."\n".
544 System::callstack(8)."\n".self::replace_parameters($sql, $params));
546 self::$error = $error;
547 self::$errorno = $errorno;
550 $a->save_timestamp($stamp, "database_write");
556 * @brief Check if data exists
558 * @param string $table Table name
559 * @param array $condition array of fields for condition
561 * @return boolean Are there rows for that condition?
563 public static function exists($table, $condition) {
570 $array_element = each($condition);
571 $array_key = $array_element['key'];
572 if (!is_int($array_key)) {
573 $fields = [$array_key];
576 $stmt = self::select($table, $fields, $condition, ['limit' => 1]);
578 if (is_bool($stmt)) {
581 $retval = (self::num_rows($stmt) > 0);
590 * Fetches the first row
592 * Please use dba::selectFirst or dba::exists whenever this is possible.
594 * @brief Fetches the first row
595 * @param string $sql SQL statement
596 * @return array first row of query
598 public static function fetch_first($sql) {
599 $params = self::getParam(func_get_args());
601 $stmt = self::p($sql, $params);
603 if (is_bool($stmt)) {
606 $retval = self::fetch($stmt);
615 * @brief Returns the number of affected rows of the last statement
617 * @return int Number of rows
619 public static function affected_rows() {
620 return self::$affected_rows;
624 * @brief Returns the number of columns of a statement
626 * @param object Statement object
627 * @return int Number of columns
629 public static function columnCount($stmt) {
630 if (!is_object($stmt)) {
633 switch (self::$driver) {
635 return $stmt->columnCount();
637 return $stmt->field_count;
642 * @brief Returns the number of rows of a statement
644 * @param PDOStatement|mysqli_result|mysqli_stmt Statement object
645 * @return int Number of rows
647 public static function num_rows($stmt) {
648 if (!is_object($stmt)) {
651 switch (self::$driver) {
653 return $stmt->rowCount();
655 return $stmt->num_rows;
661 * @brief Fetch a single row
663 * @param mixed $stmt statement object
664 * @return array current row
666 public static function fetch($stmt) {
669 $stamp1 = microtime(true);
673 if (!is_object($stmt)) {
677 switch (self::$driver) {
679 $columns = $stmt->fetch(PDO::FETCH_ASSOC);
682 if (get_class($stmt) == 'mysqli_result') {
683 $columns = $stmt->fetch_assoc();
687 // This code works, but is slow
689 // Bind the result to a result array
693 for ($x = 0; $x < $stmt->field_count; $x++) {
694 $cols[] = &$cols_num[$x];
697 call_user_func_array([$stmt, 'bind_result'], $cols);
699 if (!$stmt->fetch()) {
704 // We need to get the field names for the array keys
705 // It seems that there is no better way to do this.
706 $result = $stmt->result_metadata();
707 $fields = $result->fetch_fields();
709 foreach ($cols_num AS $param => $col) {
710 $columns[$fields[$param]->name] = $col;
714 $a->save_timestamp($stamp1, 'database');
720 * @brief Insert a row into a table
722 * @param string $table Table name
723 * @param array $param parameter array
724 * @param bool $on_duplicate_update Do an update on a duplicate entry
726 * @return boolean was the insert successfull?
728 public static function insert($table, $param, $on_duplicate_update = false) {
730 if (empty($table) || empty($param)) {
731 logger('Table and fields have to be set');
735 $sql = "INSERT INTO `".self::escape($table)."` (`".implode("`, `", array_keys($param))."`) VALUES (".
736 substr(str_repeat("?, ", count($param)), 0, -2).")";
738 if ($on_duplicate_update) {
739 $sql .= " ON DUPLICATE KEY UPDATE `".implode("` = ?, `", array_keys($param))."` = ?";
741 $values = array_values($param);
742 $param = array_merge_recursive($values, $values);
745 return self::e($sql, $param);
749 * @brief Fetch the id of the last insert command
751 * @return integer Last inserted id
753 public static function lastInsertId() {
754 switch (self::$driver) {
756 $id = self::$db->lastInsertId();
759 $id = self::$db->insert_id;
766 * @brief Locks a table for exclusive write access
768 * This function can be extended in the future to accept a table array as well.
770 * @param string $table Table name
772 * @return boolean was the lock successful?
774 public static function lock($table) {
775 // See here: https://dev.mysql.com/doc/refman/5.7/en/lock-tables-and-transactions.html
776 self::e("SET autocommit=0");
777 $success = self::e("LOCK TABLES `".self::escape($table)."` WRITE");
779 self::e("SET autocommit=1");
781 self::$in_transaction = true;
787 * @brief Unlocks all locked tables
789 * @return boolean was the unlock successful?
791 public static function unlock() {
792 // See here: https://dev.mysql.com/doc/refman/5.7/en/lock-tables-and-transactions.html
794 $success = self::e("UNLOCK TABLES");
795 self::e("SET autocommit=1");
796 self::$in_transaction = false;
801 * @brief Starts a transaction
803 * @return boolean Was the command executed successfully?
805 public static function transaction() {
806 if (!self::e('COMMIT')) {
809 if (!self::e('START TRANSACTION')) {
812 self::$in_transaction = true;
817 * @brief Does a commit
819 * @return boolean Was the command executed successfully?
821 public static function commit() {
822 if (!self::e('COMMIT')) {
825 self::$in_transaction = false;
830 * @brief Does a rollback
832 * @return boolean Was the command executed successfully?
834 public static function rollback() {
835 if (!self::e('ROLLBACK')) {
838 self::$in_transaction = false;
843 * @brief Build the array with the table relations
845 * The array is build from the database definitions in DBStructure.php
847 * This process must only be started once, since the value is cached.
849 private static function build_relation_data() {
850 $definition = DBStructure::definition();
852 foreach ($definition AS $table => $structure) {
853 foreach ($structure['fields'] AS $field => $field_struct) {
854 if (isset($field_struct['relation'])) {
855 foreach ($field_struct['relation'] AS $rel_table => $rel_field) {
856 self::$relation[$rel_table][$rel_field][$table][] = $field;
864 * @brief Delete a row from a table
866 * @param string $table Table name
867 * @param array $conditions Field condition(s)
868 * @param boolean $in_process Internal use: Only do a commit after the last delete
869 * @param array $callstack Internal use: prevent endless loops
871 * @return boolean|array was the delete successful? When $in_process is set: deletion data
873 public static function delete($table, array $conditions, $in_process = false, array &$callstack = [])
875 if (empty($table) || empty($conditions)) {
876 logger('Table and conditions have to be set');
882 // Create a key for the loop prevention
883 $key = $table . ':' . implode(':', array_keys($conditions)) . ':' . implode(':', $conditions);
885 // We quit when this key already exists in the callstack.
886 if (isset($callstack[$key])) {
890 $callstack[$key] = true;
892 $table = self::escape($table);
894 $commands[$key] = ['table' => $table, 'conditions' => $conditions];
896 // To speed up the whole process we cache the table relations
897 if (count(self::$relation) == 0) {
898 self::build_relation_data();
901 // Is there a relation entry for the table?
902 if (isset(self::$relation[$table])) {
903 // We only allow a simple "one field" relation.
904 $field = array_keys(self::$relation[$table])[0];
905 $rel_def = array_values(self::$relation[$table])[0];
907 // Create a key for preventing double queries
908 $qkey = $field . '-' . $table . ':' . implode(':', array_keys($conditions)) . ':' . implode(':', $conditions);
910 // When the search field is the relation field, we don't need to fetch the rows
911 // This is useful when the leading record is already deleted in the frontend but the rest is done in the backend
912 if ((count($conditions) == 1) && ($field == array_keys($conditions)[0])) {
913 foreach ($rel_def AS $rel_table => $rel_fields) {
914 foreach ($rel_fields AS $rel_field) {
915 $retval = self::delete($rel_table, [$rel_field => array_values($conditions)[0]], true, $callstack);
916 $commands = array_merge($commands, $retval);
919 // We quit when this key already exists in the callstack.
920 } elseif (!isset($callstack[$qkey])) {
922 $callstack[$qkey] = true;
924 // Fetch all rows that are to be deleted
925 $data = self::select($table, [$field], $conditions);
927 while ($row = self::fetch($data)) {
928 // Now we accumulate the delete commands
929 $retval = self::delete($table, [$field => $row[$field]], true, $callstack);
930 $commands = array_merge($commands, $retval);
935 // Since we had split the delete command we don't need the original command anymore
936 unset($commands[$key]);
941 // Now we finalize the process
942 $do_transaction = !self::$in_transaction;
944 if ($do_transaction) {
951 foreach ($commands AS $command) {
952 $conditions = $command['conditions'];
953 $condition_string = self::buildCondition($conditions);
955 if ((count($command['conditions']) > 1) || is_int($array_key)) {
956 $sql = "DELETE FROM `" . $command['table'] . "`" . $condition_string;
957 logger(self::replace_parameters($sql, $conditions), LOGGER_DATA);
959 if (!self::e($sql, $conditions)) {
960 if ($do_transaction) {
966 $key_table = $command['table'];
967 $key_condition = array_keys($command['conditions'])[0];
968 $value = array_values($command['conditions'])[0];
970 // Split the SQL queries in chunks of 100 values
971 // We do the $i stuff here to make the code better readable
972 $i = $counter[$key_table][$key_condition];
973 if (count($compacted[$key_table][$key_condition][$i]) > 100) {
977 $compacted[$key_table][$key_condition][$i][$value] = $value;
978 $counter[$key_table][$key_condition] = $i;
981 foreach ($compacted AS $table => $values) {
982 foreach ($values AS $field => $field_value_list) {
983 foreach ($field_value_list AS $field_values) {
984 $sql = "DELETE FROM `" . $table . "` WHERE `" . $field . "` IN (" .
985 substr(str_repeat("?, ", count($field_values)), 0, -2) . ");";
987 logger(self::replace_parameters($sql, $field_values), LOGGER_DATA);
989 if (!self::e($sql, $field_values)) {
990 if ($do_transaction) {
998 if ($do_transaction) {
1008 * @brief Updates rows
1010 * Updates rows in the database. When $old_fields is set to an array,
1011 * the system will only do an update if the fields in that array changed.
1014 * Only the values in $old_fields are compared.
1015 * This is an intentional behaviour.
1018 * We include the timestamp field in $fields but not in $old_fields.
1019 * Then the row will only get the new timestamp when the other fields had changed.
1021 * When $old_fields is set to a boolean value the system will do this compare itself.
1022 * When $old_fields is set to "true" the system will do an insert if the row doesn't exists.
1025 * Only set $old_fields to a boolean value when you are sure that you will update a single row.
1026 * When you set $old_fields to "true" then $fields must contain all relevant fields!
1028 * @param string $table Table name
1029 * @param array $fields contains the fields that are updated
1030 * @param array $condition condition array with the key values
1031 * @param array|boolean $old_fields array with the old field values that are about to be replaced (true = update on duplicate)
1033 * @return boolean was the update successfull?
1035 public static function update($table, $fields, $condition, $old_fields = []) {
1037 if (empty($table) || empty($fields) || empty($condition)) {
1038 logger('Table, fields and condition have to be set');
1042 $table = self::escape($table);
1044 $condition_string = self::buildCondition($condition);
1046 if (is_bool($old_fields)) {
1047 $do_insert = $old_fields;
1049 $old_fields = self::selectFirst($table, [], $condition);
1051 if (is_bool($old_fields)) {
1053 $values = array_merge($condition, $fields);
1054 return self::insert($table, $values, $do_insert);
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 * Retrieve a single record from a table and returns it in an associative array
1089 * @brief Retrieve a single record from a table
1090 * @param string $table
1091 * @param array $fields
1092 * @param array $condition
1093 * @param array $params
1094 * @return bool|array
1097 public static function selectFirst($table, array $fields = [], array $condition = [], $params = [])
1099 $params['limit'] = 1;
1100 $result = self::select($table, $fields, $condition, $params);
1102 if (is_bool($result)) {
1105 $row = self::fetch($result);
1106 self::close($result);
1112 * @brief Select rows from a table
1114 * @param string $table Table name
1115 * @param array $fields Array of selected fields, empty for all
1116 * @param array $condition Array of fields for condition
1117 * @param array $params Array of several parameters
1119 * @return boolean|object
1123 * $fields = array("id", "uri", "uid", "network");
1125 * $condition = array("uid" => 1, "network" => 'dspr');
1127 * $condition = array("`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr');
1129 * $params = array("order" => array("id", "received" => true), "limit" => 10);
1131 * $data = dba::select($table, $fields, $condition, $params);
1133 public static function select($table, array $fields = [], array $condition = [], array $params = [])
1139 $table = self::escape($table);
1141 if (count($fields) > 0) {
1142 $select_fields = "`" . implode("`, `", array_values($fields)) . "`";
1144 $select_fields = "*";
1147 $condition_string = self::buildCondition($condition);
1150 if (isset($params['order'])) {
1151 $order_string = " ORDER BY ";
1152 foreach ($params['order'] AS $fields => $order) {
1153 if (!is_int($fields)) {
1154 $order_string .= "`" . $fields . "` " . ($order ? "DESC" : "ASC") . ", ";
1156 $order_string .= "`" . $order . "`, ";
1159 $order_string = substr($order_string, 0, -2);
1163 if (isset($params['limit']) && is_int($params['limit'])) {
1164 $limit_string = " LIMIT " . $params['limit'];
1167 if (isset($params['limit']) && is_array($params['limit'])) {
1168 $limit_string = " LIMIT " . intval($params['limit'][0]) . ", " . intval($params['limit'][1]);
1171 $sql = "SELECT " . $select_fields . " FROM `" . $table . "`" . $condition_string . $order_string . $limit_string;
1173 $result = self::p($sql, $condition);
1179 * @brief Counts the rows from a table satisfying the provided condition
1181 * @param string $table Table name
1182 * @param array $condition array of fields for condition
1189 * $condition = ["uid" => 1, "network" => 'dspr'];
1191 * $condition = ["`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr'];
1193 * $count = dba::count($table, $condition);
1195 public static function count($table, array $condition = [])
1201 $condition_string = self::buildCondition($condition);
1203 $sql = "SELECT COUNT(*) AS `count` FROM `".$table."`".$condition_string;
1205 $row = self::fetch_first($sql, $condition);
1207 return $row['count'];
1211 * @brief Returns the SQL condition string built from the provided condition array
1213 * This function operates with two modes.
1214 * - Supplied with a filed/value associative array, it builds simple strict
1215 * equality conditions linked by AND.
1216 * - Supplied with a flat list, the first element is the condition string and
1217 * the following arguments are the values to be interpolated
1219 * $condition = ["uid" => 1, "network" => 'dspr'];
1221 * $condition = ["`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr'];
1223 * In either case, the provided array is left with the parameters only
1225 * @param array $condition
1228 private static function buildCondition(&$condition = [])
1230 $condition_string = '';
1231 if (is_array($condition) && (count($condition) > 0)) {
1232 $array_element = each($condition);
1233 $array_key = $array_element['key'];
1234 if (is_int($array_key)) {
1235 $condition_string = " WHERE ".array_shift($condition);
1238 $condition_string = "";
1239 foreach ($condition as $field => $value) {
1240 if ($condition_string != "") {
1241 $condition_string .= " AND ";
1243 if (is_array($value)) {
1244 $new_values = array_merge($new_values, array_values($value));
1245 $placeholders = substr(str_repeat("?, ", count($value)), 0, -2);
1246 $condition_string .= "`" . $field . "` IN (" . $placeholders . ")";
1248 $new_values[$field] = $value;
1249 $condition_string .= "`" . $field . "` = ?";
1252 $condition_string = " WHERE " . $condition_string;
1253 $condition = $new_values;
1257 return $condition_string;
1261 * @brief Fills an array with data from a query
1263 * @param object $stmt statement object
1264 * @return array Data array
1266 public static function inArray($stmt, $do_close = true) {
1267 if (is_bool($stmt)) {
1272 while ($row = self::fetch($stmt)) {
1282 * @brief Returns the error number of the last query
1284 * @return string Error number (0 if no error)
1286 public static function errorNo() {
1287 return self::$errorno;
1291 * @brief Returns the error message of the last query
1293 * @return string Error message ('' if no error)
1295 public static function errorMessage() {
1296 return self::$error;
1300 * @brief Closes the current statement
1302 * @param object $stmt statement object
1303 * @return boolean was the close successful?
1305 public static function close($stmt) {
1308 $stamp1 = microtime(true);
1310 if (!is_object($stmt)) {
1314 switch (self::$driver) {
1316 $ret = $stmt->closeCursor();
1319 $stmt->free_result();
1320 $ret = $stmt->close();
1324 $a->save_timestamp($stamp1, 'database');
1330 function dbesc($str) {
1331 if (dba::$connected) {
1332 return(dba::escape($str));
1334 return(str_replace("'","\\'",$str));
1339 * @brief execute SQL query with printf style args - deprecated
1341 * Please use the dba:: functions instead:
1342 * dba::select, dba::exists, dba::insert
1343 * dba::delete, dba::update, dba::p, dba::e
1345 * @param $args Query parameters (1 to N parameters of different types)
1346 * @return array|bool Query array
1349 $args = func_get_args();
1352 if (!dba::$connected) {
1356 $sql = dba::clean_query($sql);
1357 $sql = dba::any_value_fallback($sql);
1359 $stmt = @vsprintf($sql, $args);
1361 $ret = dba::p($stmt);
1363 if (is_bool($ret)) {
1367 $columns = dba::columnCount($ret);
1369 $data = dba::inArray($ret);
1371 if ((count($data) == 0) && ($columns == 0)) {
1378 function dba_timer() {
1379 return microtime(true);