4 use Friendica\Core\L10n;
5 use Friendica\Core\System;
6 use Friendica\Database\DBM;
7 use Friendica\Database\DBStructure;
8 use Friendica\Util\DateTimeFormat;
11 * @class MySQL database class
13 * This class is for the low level database stuff that does driver specific things.
17 public static $connected = false;
19 private static $_server_info = '';
21 private static $driver;
22 private static $error = false;
23 private static $errorno = 0;
24 private static $affected_rows = 0;
25 private static $in_transaction = false;
26 private static $relation = [];
28 public static function connect($serveraddr, $user, $pass, $db) {
29 if (!is_null(self::$db)) {
35 $stamp1 = microtime(true);
37 $serveraddr = trim($serveraddr);
39 $serverdata = explode(':', $serveraddr);
40 $server = $serverdata[0];
42 if (count($serverdata) > 1) {
43 $port = trim($serverdata[1]);
46 $server = trim($server);
51 if (!(strlen($server) && strlen($user))) {
55 if (class_exists('\PDO') && in_array('mysql', PDO::getAvailableDrivers())) {
56 self::$driver = 'pdo';
57 $connect = "mysql:host=".$server.";dbname=".$db;
60 $connect .= ";port=".$port;
63 if (isset($a->config["system"]["db_charset"])) {
64 $connect .= ";charset=".$a->config["system"]["db_charset"];
67 self::$db = @new PDO($connect, $user, $pass);
68 self::$connected = true;
69 } catch (PDOException $e) {
73 if (!self::$connected && class_exists('mysqli')) {
74 self::$driver = 'mysqli';
75 self::$db = @new mysqli($server, $user, $pass, $db, $port);
76 if (!mysqli_connect_errno()) {
77 self::$connected = true;
79 if (isset($a->config["system"]["db_charset"])) {
80 self::$db->set_charset($a->config["system"]["db_charset"]);
85 // No suitable SQL driver was found.
86 if (!self::$connected) {
90 $a->save_timestamp($stamp1, "network");
92 return self::$connected;
96 * Return the database object.
99 public static function get_db()
105 * @brief Returns the MySQL server version string
107 * This function discriminate between the deprecated mysql API and the current
108 * object-oriented mysqli API. Example of returned string: 5.5.46-0+deb8u1
112 public static function server_info() {
113 if (self::$_server_info == '') {
114 switch (self::$driver) {
116 self::$_server_info = self::$db->getAttribute(PDO::ATTR_SERVER_VERSION);
119 self::$_server_info = self::$db->server_info;
123 return self::$_server_info;
127 * @brief Returns the selected database name
131 public static function database_name() {
132 $ret = self::p("SELECT DATABASE() AS `db`");
133 $data = self::inArray($ret);
134 return $data[0]['db'];
138 * @brief Analyze a database query and log this if some conditions are met.
140 * @param string $query The database query that will be analyzed
142 private static function logIndex($query) {
145 if (empty($a->config["system"]["db_log_index"])) {
149 // Don't explain an explain statement
150 if (strtolower(substr($query, 0, 7)) == "explain") {
154 // Only do the explain on "select", "update" and "delete"
155 if (!in_array(strtolower(substr($query, 0, 6)), ["select", "update", "delete"])) {
159 $r = self::p("EXPLAIN ".$query);
160 if (!DBM::is_result($r)) {
164 $watchlist = explode(',', $a->config["system"]["db_log_index_watch"]);
165 $blacklist = explode(',', $a->config["system"]["db_log_index_blacklist"]);
167 while ($row = dba::fetch($r)) {
168 if ((intval($a->config["system"]["db_loglimit_index"]) > 0)) {
169 $log = (in_array($row['key'], $watchlist) &&
170 ($row['rows'] >= intval($a->config["system"]["db_loglimit_index"])));
175 if ((intval($a->config["system"]["db_loglimit_index_high"]) > 0) && ($row['rows'] >= intval($a->config["system"]["db_loglimit_index_high"]))) {
179 if (in_array($row['key'], $blacklist) || ($row['key'] == "")) {
184 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
185 @file_put_contents($a->config["system"]["db_log_index"], DateTimeFormat::utcNow()."\t".
186 $row['key']."\t".$row['rows']."\t".$row['Extra']."\t".
187 basename($backtrace[1]["file"])."\t".
188 $backtrace[1]["line"]."\t".$backtrace[2]["function"]."\t".
189 substr($query, 0, 2000)."\n", FILE_APPEND);
194 public static function escape($str) {
195 switch (self::$driver) {
197 return substr(@self::$db->quote($str, PDO::PARAM_STR), 1, -1);
199 return @self::$db->real_escape_string($str);
203 public static function connected() {
206 switch (self::$driver) {
208 $r = dba::p("SELECT 1");
209 if (DBM::is_result($r)) {
210 $row = dba::inArray($r);
211 $connected = ($row[0]['1'] == '1');
215 $connected = self::$db->ping();
222 * @brief Replaces ANY_VALUE() function by MIN() function,
223 * if the database server does not support ANY_VALUE().
225 * Considerations for Standard SQL, or MySQL with ONLY_FULL_GROUP_BY (default since 5.7.5).
226 * ANY_VALUE() is available from MySQL 5.7.5 https://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html
227 * A standard fall-back is to use MIN().
229 * @param string $sql An SQL string without the values
230 * @return string The input SQL string modified if necessary.
232 public static function any_value_fallback($sql) {
233 $server_info = self::server_info();
234 if (version_compare($server_info, '5.7.5', '<') ||
235 (stripos($server_info, 'MariaDB') !== false)) {
236 $sql = str_ireplace('ANY_VALUE(', 'MIN(', $sql);
242 * @brief beautifies the query - useful for "SHOW PROCESSLIST"
244 * This is safe when we bind the parameters later.
245 * The parameter values aren't part of the SQL.
247 * @param string $sql An SQL string without the values
248 * @return string The input SQL string modified if necessary.
250 public static function clean_query($sql) {
251 $search = ["\t", "\n", "\r", " "];
252 $replace = [' ', ' ', ' ', ' '];
255 $sql = str_replace($search, $replace, $sql);
256 } while ($oldsql != $sql);
263 * @brief Replaces the ? placeholders with the parameters in the $args array
265 * @param string $sql SQL query
266 * @param array $args The parameters that are to replace the ? placeholders
267 * @return string The replaced SQL query
269 private static function replaceParameters($sql, $args) {
271 foreach ($args AS $param => $value) {
272 if (is_int($args[$param]) || is_float($args[$param])) {
273 $replace = intval($args[$param]);
275 $replace = "'".self::escape($args[$param])."'";
278 $pos = strpos($sql, '?', $offset);
279 if ($pos !== false) {
280 $sql = substr_replace($sql, $replace, $pos, 1);
282 $offset = $pos + strlen($replace);
288 * @brief Convert parameter array to an universal form
289 * @param array $args Parameter array
290 * @return array universalized parameter array
292 private static function getParam($args) {
295 // When the second function parameter is an array then use this as the parameter array
296 if ((count($args) > 0) && (is_array($args[1]))) {
304 * @brief Executes a prepared statement that returns data
305 * @usage Example: $r = p("SELECT * FROM `item` WHERE `guid` = ?", $guid);
307 * Please only use it with complicated queries.
308 * For all regular queries please use dba::select or dba::exists
310 * @param string $sql SQL statement
311 * @return bool|object statement object
313 public static function p($sql) {
316 $stamp1 = microtime(true);
318 $params = self::getParam(func_get_args());
320 // Renumber the array keys to be sure that they fit
323 foreach ($params AS $param) {
324 // Avoid problems with some MySQL servers and boolean values. See issue #3645
325 if (is_bool($param)) {
326 $param = (int)$param;
328 $args[++$i] = $param;
331 if (!self::$connected) {
335 if ((substr_count($sql, '?') != count($args)) && (count($args) > 0)) {
336 // Question: Should we continue or stop the query here?
337 logger('Parameter mismatch. Query "'.$sql.'" - Parameters '.print_r($args, true), LOGGER_DEBUG);
340 $sql = self::clean_query($sql);
341 $sql = self::any_value_fallback($sql);
345 if (x($a->config,'system') && x($a->config['system'], 'db_callstack')) {
346 $sql = "/*".System::callstack()." */ ".$sql;
351 self::$affected_rows = 0;
353 // We have to make some things different if this function is called from "e"
354 $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2);
356 if (isset($trace[1])) {
357 $called_from = $trace[1];
359 // We use just something that is defined to avoid warnings
360 $called_from = $trace[0];
362 // We are having an own error logging in the function "e"
363 $called_from_e = ($called_from['function'] == 'e');
365 switch (self::$driver) {
367 // If there are no arguments we use "query"
368 if (count($args) == 0) {
369 if (!$retval = self::$db->query($sql)) {
370 $errorInfo = self::$db->errorInfo();
371 self::$error = $errorInfo[2];
372 self::$errorno = $errorInfo[1];
376 self::$affected_rows = $retval->rowCount();
380 if (!$stmt = self::$db->prepare($sql)) {
381 $errorInfo = self::$db->errorInfo();
382 self::$error = $errorInfo[2];
383 self::$errorno = $errorInfo[1];
388 foreach ($args AS $param => $value) {
389 $stmt->bindParam($param, $args[$param]);
392 if (!$stmt->execute()) {
393 $errorInfo = $stmt->errorInfo();
394 self::$error = $errorInfo[2];
395 self::$errorno = $errorInfo[1];
399 self::$affected_rows = $retval->rowCount();
403 // There are SQL statements that cannot be executed with a prepared statement
404 $parts = explode(' ', $orig_sql);
405 $command = strtolower($parts[0]);
406 $can_be_prepared = in_array($command, ['select', 'update', 'insert', 'delete']);
408 // The fallback routine is called as well when there are no arguments
409 if (!$can_be_prepared || (count($args) == 0)) {
410 $retval = self::$db->query(self::replaceParameters($sql, $args));
411 if (self::$db->errno) {
412 self::$error = self::$db->error;
413 self::$errorno = self::$db->errno;
416 if (isset($retval->num_rows)) {
417 self::$affected_rows = $retval->num_rows;
419 self::$affected_rows = self::$db->affected_rows;
425 $stmt = self::$db->stmt_init();
427 if (!$stmt->prepare($sql)) {
428 self::$error = $stmt->error;
429 self::$errorno = $stmt->errno;
436 foreach ($args AS $param => $value) {
437 if (is_int($args[$param])) {
439 } elseif (is_float($args[$param])) {
441 } elseif (is_string($args[$param])) {
446 $values[] = &$args[$param];
449 if (count($values) > 0) {
450 array_unshift($values, $params);
451 call_user_func_array([$stmt, 'bind_param'], $values);
454 if (!$stmt->execute()) {
455 self::$error = self::$db->error;
456 self::$errorno = self::$db->errno;
459 $stmt->store_result();
461 self::$affected_rows = $retval->affected_rows;
466 // We are having an own error logging in the function "e"
467 if ((self::$errorno != 0) && !$called_from_e) {
468 // We have to preserve the error code, somewhere in the logging it get lost
469 $error = self::$error;
470 $errorno = self::$errorno;
472 logger('DB Error '.self::$errorno.': '.self::$error."\n".
473 System::callstack(8)."\n".self::replaceParameters($sql, $params));
475 self::$error = $error;
476 self::$errorno = $errorno;
479 $a->save_timestamp($stamp1, 'database');
481 if (x($a->config,'system') && x($a->config['system'], 'db_log')) {
483 $stamp2 = microtime(true);
484 $duration = (float)($stamp2 - $stamp1);
486 if (($duration > $a->config["system"]["db_loglimit"])) {
487 $duration = round($duration, 3);
488 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
490 @file_put_contents($a->config["system"]["db_log"], DateTimeFormat::utcNow()."\t".$duration."\t".
491 basename($backtrace[1]["file"])."\t".
492 $backtrace[1]["line"]."\t".$backtrace[2]["function"]."\t".
493 substr(self::replaceParameters($sql, $args), 0, 2000)."\n", FILE_APPEND);
500 * @brief Executes a prepared statement like UPDATE or INSERT that doesn't return data
502 * Please use dba::delete, dba::insert, dba::update, ... instead
504 * @param string $sql SQL statement
505 * @return boolean Was the query successfull? False is returned only if an error occurred
507 public static function e($sql) {
510 $stamp = microtime(true);
512 $params = self::getParam(func_get_args());
514 // In a case of a deadlock we are repeating the query 20 times
518 $stmt = self::p($sql, $params);
520 if (is_bool($stmt)) {
522 } elseif (is_object($stmt)) {
530 } while ((self::$errorno == 1213) && (--$timeout > 0));
532 if (self::$errorno != 0) {
533 // We have to preserve the error code, somewhere in the logging it get lost
534 $error = self::$error;
535 $errorno = self::$errorno;
537 logger('DB Error '.self::$errorno.': '.self::$error."\n".
538 System::callstack(8)."\n".self::replaceParameters($sql, $params));
540 self::$error = $error;
541 self::$errorno = $errorno;
544 $a->save_timestamp($stamp, "database_write");
550 * @brief Check if data exists
552 * @param string $table Table name
553 * @param array $condition array of fields for condition
555 * @return boolean Are there rows for that condition?
557 public static function exists($table, $condition) {
565 $first_key = key($condition);
566 if (!is_int($first_key)) {
567 $fields = [$first_key];
570 $stmt = self::select($table, $fields, $condition, ['limit' => 1]);
572 if (is_bool($stmt)) {
575 $retval = (self::num_rows($stmt) > 0);
584 * Fetches the first row
586 * Please use dba::selectFirst or dba::exists whenever this is possible.
588 * @brief Fetches the first row
589 * @param string $sql SQL statement
590 * @return array first row of query
592 public static function fetch_first($sql) {
593 $params = self::getParam(func_get_args());
595 $stmt = self::p($sql, $params);
597 if (is_bool($stmt)) {
600 $retval = self::fetch($stmt);
609 * @brief Returns the number of affected rows of the last statement
611 * @return int Number of rows
613 public static function affected_rows() {
614 return self::$affected_rows;
618 * @brief Returns the number of columns of a statement
620 * @param object Statement object
621 * @return int Number of columns
623 public static function columnCount($stmt) {
624 if (!is_object($stmt)) {
627 switch (self::$driver) {
629 return $stmt->columnCount();
631 return $stmt->field_count;
636 * @brief Returns the number of rows of a statement
638 * @param PDOStatement|mysqli_result|mysqli_stmt Statement object
639 * @return int Number of rows
641 public static function num_rows($stmt) {
642 if (!is_object($stmt)) {
645 switch (self::$driver) {
647 return $stmt->rowCount();
649 return $stmt->num_rows;
655 * @brief Fetch a single row
657 * @param mixed $stmt statement object
658 * @return array current row
660 public static function fetch($stmt) {
663 $stamp1 = microtime(true);
667 if (!is_object($stmt)) {
671 switch (self::$driver) {
673 $columns = $stmt->fetch(PDO::FETCH_ASSOC);
676 if (get_class($stmt) == 'mysqli_result') {
677 $columns = $stmt->fetch_assoc();
681 // This code works, but is slow
683 // Bind the result to a result array
687 for ($x = 0; $x < $stmt->field_count; $x++) {
688 $cols[] = &$cols_num[$x];
691 call_user_func_array([$stmt, 'bind_result'], $cols);
693 if (!$stmt->fetch()) {
698 // We need to get the field names for the array keys
699 // It seems that there is no better way to do this.
700 $result = $stmt->result_metadata();
701 $fields = $result->fetch_fields();
703 foreach ($cols_num AS $param => $col) {
704 $columns[$fields[$param]->name] = $col;
708 $a->save_timestamp($stamp1, 'database');
714 * @brief Insert a row into a table
716 * @param string $table Table name
717 * @param array $param parameter array
718 * @param bool $on_duplicate_update Do an update on a duplicate entry
720 * @return boolean was the insert successfull?
722 public static function insert($table, $param, $on_duplicate_update = false) {
724 if (empty($table) || empty($param)) {
725 logger('Table and fields have to be set');
729 $sql = "INSERT INTO `".self::escape($table)."` (`".implode("`, `", array_keys($param))."`) VALUES (".
730 substr(str_repeat("?, ", count($param)), 0, -2).")";
732 if ($on_duplicate_update) {
733 $sql .= " ON DUPLICATE KEY UPDATE `".implode("` = ?, `", array_keys($param))."` = ?";
735 $values = array_values($param);
736 $param = array_merge_recursive($values, $values);
739 return self::e($sql, $param);
743 * @brief Fetch the id of the last insert command
745 * @return integer Last inserted id
747 public static function lastInsertId() {
748 switch (self::$driver) {
750 $id = self::$db->lastInsertId();
753 $id = self::$db->insert_id;
760 * @brief Locks a table for exclusive write access
762 * This function can be extended in the future to accept a table array as well.
764 * @param string $table Table name
766 * @return boolean was the lock successful?
768 public static function lock($table) {
769 // See here: https://dev.mysql.com/doc/refman/5.7/en/lock-tables-and-transactions.html
770 self::e("SET autocommit=0");
771 $success = self::e("LOCK TABLES `".self::escape($table)."` WRITE");
773 self::e("SET autocommit=1");
775 self::$in_transaction = true;
781 * @brief Unlocks all locked tables
783 * @return boolean was the unlock successful?
785 public static function unlock() {
786 // See here: https://dev.mysql.com/doc/refman/5.7/en/lock-tables-and-transactions.html
788 $success = self::e("UNLOCK TABLES");
789 self::e("SET autocommit=1");
790 self::$in_transaction = false;
795 * @brief Starts a transaction
797 * @return boolean Was the command executed successfully?
799 public static function transaction() {
800 if (!self::e('COMMIT')) {
803 if (!self::e('START TRANSACTION')) {
806 self::$in_transaction = true;
811 * @brief Does a commit
813 * @return boolean Was the command executed successfully?
815 public static function commit() {
816 if (!self::e('COMMIT')) {
819 self::$in_transaction = false;
824 * @brief Does a rollback
826 * @return boolean Was the command executed successfully?
828 public static function rollback() {
829 if (!self::e('ROLLBACK')) {
832 self::$in_transaction = false;
837 * @brief Build the array with the table relations
839 * The array is build from the database definitions in DBStructure.php
841 * This process must only be started once, since the value is cached.
843 private static function buildRelationData() {
844 $definition = DBStructure::definition();
846 foreach ($definition AS $table => $structure) {
847 foreach ($structure['fields'] AS $field => $field_struct) {
848 if (isset($field_struct['relation'])) {
849 foreach ($field_struct['relation'] AS $rel_table => $rel_field) {
850 self::$relation[$rel_table][$rel_field][$table][] = $field;
858 * @brief Delete a row from a table
860 * @param string $table Table name
861 * @param array $conditions Field condition(s)
862 * @param array $options
863 * - cascade: If true we delete records in other tables that depend on the one we're deleting through
864 * relations (default: true)
865 * @param boolean $in_process Internal use: Only do a commit after the last delete
866 * @param array $callstack Internal use: prevent endless loops
868 * @return boolean|array was the delete successful? When $in_process is set: deletion data
870 public static function delete($table, array $conditions, array $options = [], $in_process = false, array &$callstack = [])
872 if (empty($table) || empty($conditions)) {
873 logger('Table and conditions have to be set');
879 // Create a key for the loop prevention
880 $key = $table . ':' . implode(':', array_keys($conditions)) . ':' . implode(':', $conditions);
882 // We quit when this key already exists in the callstack.
883 if (isset($callstack[$key])) {
887 $callstack[$key] = true;
889 $table = self::escape($table);
891 $commands[$key] = ['table' => $table, 'conditions' => $conditions];
893 $cascade = defaults($options, 'cascade', true);
895 // To speed up the whole process we cache the table relations
896 if ($cascade && count(self::$relation) == 0) {
897 self::buildRelationData();
900 // Is there a relation entry for the table?
901 if ($cascade && isset(self::$relation[$table])) {
902 // We only allow a simple "one field" relation.
903 $field = array_keys(self::$relation[$table])[0];
904 $rel_def = array_values(self::$relation[$table])[0];
906 // Create a key for preventing double queries
907 $qkey = $field . '-' . $table . ':' . implode(':', array_keys($conditions)) . ':' . implode(':', $conditions);
909 // When the search field is the relation field, we don't need to fetch the rows
910 // This is useful when the leading record is already deleted in the frontend but the rest is done in the backend
911 if ((count($conditions) == 1) && ($field == array_keys($conditions)[0])) {
912 foreach ($rel_def AS $rel_table => $rel_fields) {
913 foreach ($rel_fields AS $rel_field) {
914 $retval = self::delete($rel_table, [$rel_field => array_values($conditions)[0]], $options, true, $callstack);
915 $commands = array_merge($commands, $retval);
918 // We quit when this key already exists in the callstack.
919 } elseif (!isset($callstack[$qkey])) {
921 $callstack[$qkey] = true;
923 // Fetch all rows that are to be deleted
924 $data = self::select($table, [$field], $conditions);
926 while ($row = self::fetch($data)) {
927 // Now we accumulate the delete commands
928 $retval = self::delete($table, [$field => $row[$field]], $options, true, $callstack);
929 $commands = array_merge($commands, $retval);
934 // Since we had split the delete command we don't need the original command anymore
935 unset($commands[$key]);
940 // Now we finalize the process
941 $do_transaction = !self::$in_transaction;
943 if ($do_transaction) {
950 foreach ($commands AS $command) {
951 $conditions = $command['conditions'];
953 $first_key = key($conditions);
955 $condition_string = self::buildCondition($conditions);
957 if ((count($command['conditions']) > 1) || is_int($first_key)) {
958 $sql = "DELETE FROM `" . $command['table'] . "`" . $condition_string;
959 logger(self::replaceParameters($sql, $conditions), LOGGER_DATA);
961 if (!self::e($sql, $conditions)) {
962 if ($do_transaction) {
968 $key_table = $command['table'];
969 $key_condition = array_keys($command['conditions'])[0];
970 $value = array_values($command['conditions'])[0];
972 // Split the SQL queries in chunks of 100 values
973 // We do the $i stuff here to make the code better readable
974 $i = $counter[$key_table][$key_condition];
975 if (isset($compacted[$key_table][$key_condition][$i]) && count($compacted[$key_table][$key_condition][$i]) > 100) {
979 $compacted[$key_table][$key_condition][$i][$value] = $value;
980 $counter[$key_table][$key_condition] = $i;
983 foreach ($compacted AS $table => $values) {
984 foreach ($values AS $field => $field_value_list) {
985 foreach ($field_value_list AS $field_values) {
986 $sql = "DELETE FROM `" . $table . "` WHERE `" . $field . "` IN (" .
987 substr(str_repeat("?, ", count($field_values)), 0, -2) . ");";
989 logger(self::replaceParameters($sql, $field_values), LOGGER_DATA);
991 if (!self::e($sql, $field_values)) {
992 if ($do_transaction) {
1000 if ($do_transaction) {
1010 * @brief Updates rows
1012 * Updates rows in the database. When $old_fields is set to an array,
1013 * the system will only do an update if the fields in that array changed.
1016 * Only the values in $old_fields are compared.
1017 * This is an intentional behaviour.
1020 * We include the timestamp field in $fields but not in $old_fields.
1021 * Then the row will only get the new timestamp when the other fields had changed.
1023 * When $old_fields is set to a boolean value the system will do this compare itself.
1024 * When $old_fields is set to "true" the system will do an insert if the row doesn't exists.
1027 * Only set $old_fields to a boolean value when you are sure that you will update a single row.
1028 * When you set $old_fields to "true" then $fields must contain all relevant fields!
1030 * @param string $table Table name
1031 * @param array $fields contains the fields that are updated
1032 * @param array $condition condition array with the key values
1033 * @param array|boolean $old_fields array with the old field values that are about to be replaced (true = update on duplicate)
1035 * @return boolean was the update successfull?
1037 public static function update($table, $fields, $condition, $old_fields = []) {
1039 if (empty($table) || empty($fields) || empty($condition)) {
1040 logger('Table, fields and condition have to be set');
1044 $table = self::escape($table);
1046 $condition_string = self::buildCondition($condition);
1048 if (is_bool($old_fields)) {
1049 $do_insert = $old_fields;
1051 $old_fields = self::selectFirst($table, [], $condition);
1053 if (is_bool($old_fields)) {
1055 $values = array_merge($condition, $fields);
1056 return self::insert($table, $values, $do_insert);
1062 $do_update = (count($old_fields) == 0);
1064 foreach ($old_fields AS $fieldname => $content) {
1065 if (isset($fields[$fieldname])) {
1066 if ($fields[$fieldname] == $content) {
1067 unset($fields[$fieldname]);
1074 if (!$do_update || (count($fields) == 0)) {
1078 $sql = "UPDATE `".$table."` SET `".
1079 implode("` = ?, `", array_keys($fields))."` = ?".$condition_string;
1081 $params1 = array_values($fields);
1082 $params2 = array_values($condition);
1083 $params = array_merge_recursive($params1, $params2);
1085 return self::e($sql, $params);
1089 * Retrieve a single record from a table and returns it in an associative array
1091 * @brief Retrieve a single record from a table
1092 * @param string $table
1093 * @param array $fields
1094 * @param array $condition
1095 * @param array $params
1096 * @return bool|array
1099 public static function selectFirst($table, array $fields = [], array $condition = [], $params = [])
1101 $params['limit'] = 1;
1102 $result = self::select($table, $fields, $condition, $params);
1104 if (is_bool($result)) {
1107 $row = self::fetch($result);
1108 self::close($result);
1114 * @brief Select rows from a table
1116 * @param string $table Table name
1117 * @param array $fields Array of selected fields, empty for all
1118 * @param array $condition Array of fields for condition
1119 * @param array $params Array of several parameters
1121 * @return boolean|object
1125 * $fields = array("id", "uri", "uid", "network");
1127 * $condition = array("uid" => 1, "network" => 'dspr');
1129 * $condition = array("`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr');
1131 * $params = array("order" => array("id", "received" => true), "limit" => 10);
1133 * $data = dba::select($table, $fields, $condition, $params);
1135 public static function select($table, array $fields = [], array $condition = [], array $params = [])
1141 $table = self::escape($table);
1143 if (count($fields) > 0) {
1144 $select_fields = "`" . implode("`, `", array_values($fields)) . "`";
1146 $select_fields = "*";
1149 $condition_string = self::buildCondition($condition);
1152 if (isset($params['order'])) {
1153 $order_string = " ORDER BY ";
1154 foreach ($params['order'] AS $fields => $order) {
1155 if (!is_int($fields)) {
1156 $order_string .= "`" . $fields . "` " . ($order ? "DESC" : "ASC") . ", ";
1158 $order_string .= "`" . $order . "`, ";
1161 $order_string = substr($order_string, 0, -2);
1165 if (isset($params['limit']) && is_int($params['limit'])) {
1166 $limit_string = " LIMIT " . $params['limit'];
1169 if (isset($params['limit']) && is_array($params['limit'])) {
1170 $limit_string = " LIMIT " . intval($params['limit'][0]) . ", " . intval($params['limit'][1]);
1173 $sql = "SELECT " . $select_fields . " FROM `" . $table . "`" . $condition_string . $order_string . $limit_string;
1175 $result = self::p($sql, $condition);
1181 * @brief Counts the rows from a table satisfying the provided condition
1183 * @param string $table Table name
1184 * @param array $condition array of fields for condition
1191 * $condition = ["uid" => 1, "network" => 'dspr'];
1193 * $condition = ["`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr'];
1195 * $count = dba::count($table, $condition);
1197 public static function count($table, array $condition = [])
1203 $condition_string = self::buildCondition($condition);
1205 $sql = "SELECT COUNT(*) AS `count` FROM `".$table."`".$condition_string;
1207 $row = self::fetch_first($sql, $condition);
1209 return $row['count'];
1213 * @brief Returns the SQL condition string built from the provided condition array
1215 * This function operates with two modes.
1216 * - Supplied with a filed/value associative array, it builds simple strict
1217 * equality conditions linked by AND.
1218 * - Supplied with a flat list, the first element is the condition string and
1219 * the following arguments are the values to be interpolated
1221 * $condition = ["uid" => 1, "network" => 'dspr'];
1223 * $condition = ["`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr'];
1225 * In either case, the provided array is left with the parameters only
1227 * @param array $condition
1230 private static function buildCondition(array &$condition = [])
1232 $condition_string = '';
1233 if (count($condition) > 0) {
1235 $first_key = key($condition);
1236 if (is_int($first_key)) {
1237 $condition_string = " WHERE ".array_shift($condition);
1240 $condition_string = "";
1241 foreach ($condition as $field => $value) {
1242 if ($condition_string != "") {
1243 $condition_string .= " AND ";
1245 if (is_array($value)) {
1246 $new_values = array_merge($new_values, array_values($value));
1247 $placeholders = substr(str_repeat("?, ", count($value)), 0, -2);
1248 $condition_string .= "`" . $field . "` IN (" . $placeholders . ")";
1250 $new_values[$field] = $value;
1251 $condition_string .= "`" . $field . "` = ?";
1254 $condition_string = " WHERE " . $condition_string;
1255 $condition = $new_values;
1259 return $condition_string;
1263 * @brief Fills an array with data from a query
1265 * @param object $stmt statement object
1266 * @return array Data array
1268 public static function inArray($stmt, $do_close = true) {
1269 if (is_bool($stmt)) {
1274 while ($row = self::fetch($stmt)) {
1284 * @brief Returns the error number of the last query
1286 * @return string Error number (0 if no error)
1288 public static function errorNo() {
1289 return self::$errorno;
1293 * @brief Returns the error message of the last query
1295 * @return string Error message ('' if no error)
1297 public static function errorMessage() {
1298 return self::$error;
1302 * @brief Closes the current statement
1304 * @param object $stmt statement object
1305 * @return boolean was the close successful?
1307 public static function close($stmt) {
1310 $stamp1 = microtime(true);
1312 if (!is_object($stmt)) {
1316 switch (self::$driver) {
1318 $ret = $stmt->closeCursor();
1321 $stmt->free_result();
1322 $ret = $stmt->close();
1326 $a->save_timestamp($stamp1, 'database');
1332 function dbesc($str) {
1333 if (dba::$connected) {
1334 return(dba::escape($str));
1336 return(str_replace("'","\\'",$str));
1341 * @brief execute SQL query with printf style args - deprecated
1343 * Please use the dba:: functions instead:
1344 * dba::select, dba::exists, dba::insert
1345 * dba::delete, dba::update, dba::p, dba::e
1347 * @param $args Query parameters (1 to N parameters of different types)
1348 * @return array|bool Query array
1351 $args = func_get_args();
1354 if (!dba::$connected) {
1358 $sql = dba::clean_query($sql);
1359 $sql = dba::any_value_fallback($sql);
1361 $stmt = @vsprintf($sql, $args);
1363 $ret = dba::p($stmt);
1365 if (is_bool($ret)) {
1369 $columns = dba::columnCount($ret);
1371 $data = dba::inArray($ret);
1373 if ((count($data) == 0) && ($columns == 0)) {
1380 function dba_timer() {
1381 return microtime(true);