2 use Friendica\Core\System;
3 use Friendica\Database\DBM;
4 use Friendica\Database\DBStructure;
6 require_once('include/datetime.php');
9 * @class MySQL database class
11 * This class is for the low level database stuff that does driver specific things.
15 public static $connected = true;
17 private static $_server_info = '';
19 private static $driver;
20 private static $error = false;
21 private static $errorno = 0;
22 private static $affected_rows = 0;
23 private static $in_transaction = false;
24 private static $relation = [];
26 public static function connect($serveraddr, $user, $pass, $db, $install = false) {
27 if (!is_null(self::$db)) {
33 $stamp1 = microtime(true);
35 $serveraddr = trim($serveraddr);
37 $serverdata = explode(':', $serveraddr);
38 $server = $serverdata[0];
40 if (count($serverdata) > 1) {
41 $port = trim($serverdata[1]);
44 $server = trim($server);
49 if (!(strlen($server) && strlen($user))) {
50 self::$connected = false;
56 if (strlen($server) && ($server !== 'localhost') && ($server !== '127.0.0.1')) {
57 if (! dns_get_record($server, DNS_A + DNS_CNAME + DNS_PTR)) {
58 self::$error = sprintf(t('Cannot locate DNS info for database server \'%s\''), $server);
59 self::$connected = false;
66 if (class_exists('\PDO') && in_array('mysql', PDO::getAvailableDrivers())) {
67 self::$driver = 'pdo';
68 $connect = "mysql:host=".$server.";dbname=".$db;
71 $connect .= ";port=".$port;
74 if (isset($a->config["system"]["db_charset"])) {
75 $connect .= ";charset=".$a->config["system"]["db_charset"];
78 self::$db = @new PDO($connect, $user, $pass);
79 self::$connected = true;
80 } catch (PDOException $e) {
81 self::$connected = false;
85 if (!self::$connected && class_exists('mysqli')) {
86 self::$driver = 'mysqli';
87 self::$db = @new mysqli($server, $user, $pass, $db, $port);
88 if (!mysqli_connect_errno()) {
89 self::$connected = true;
91 if (isset($a->config["system"]["db_charset"])) {
92 self::$db->set_charset($a->config["system"]["db_charset"]);
97 // No suitable SQL driver was found.
98 if (!self::$connected) {
101 System::unavailable();
104 $a->save_timestamp($stamp1, "network");
110 * @brief Returns the MySQL server version string
112 * This function discriminate between the deprecated mysql API and the current
113 * object-oriented mysqli API. Example of returned string: 5.5.46-0+deb8u1
117 public static function server_info() {
118 if (self::$_server_info == '') {
119 switch (self::$driver) {
121 self::$_server_info = self::$db->getAttribute(PDO::ATTR_SERVER_VERSION);
124 self::$_server_info = self::$db->server_info;
128 return self::$_server_info;
132 * @brief Returns the selected database name
136 public static function database_name() {
137 $ret = self::p("SELECT DATABASE() AS `db`");
138 $data = self::inArray($ret);
139 return $data[0]['db'];
143 * @brief Analyze a database query and log this if some conditions are met.
145 * @param string $query The database query that will be analyzed
147 private static function log_index($query) {
150 if (empty($a->config["system"]["db_log_index"])) {
154 // Don't explain an explain statement
155 if (strtolower(substr($query, 0, 7)) == "explain") {
159 // Only do the explain on "select", "update" and "delete"
160 if (!in_array(strtolower(substr($query, 0, 6)), ["select", "update", "delete"])) {
164 $r = self::p("EXPLAIN ".$query);
165 if (!DBM::is_result($r)) {
169 $watchlist = explode(',', $a->config["system"]["db_log_index_watch"]);
170 $blacklist = explode(',', $a->config["system"]["db_log_index_blacklist"]);
172 while ($row = dba::fetch($r)) {
173 if ((intval($a->config["system"]["db_loglimit_index"]) > 0)) {
174 $log = (in_array($row['key'], $watchlist) &&
175 ($row['rows'] >= intval($a->config["system"]["db_loglimit_index"])));
180 if ((intval($a->config["system"]["db_loglimit_index_high"]) > 0) && ($row['rows'] >= intval($a->config["system"]["db_loglimit_index_high"]))) {
184 if (in_array($row['key'], $blacklist) || ($row['key'] == "")) {
189 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
190 @file_put_contents($a->config["system"]["db_log_index"], datetime_convert()."\t".
191 $row['key']."\t".$row['rows']."\t".$row['Extra']."\t".
192 basename($backtrace[1]["file"])."\t".
193 $backtrace[1]["line"]."\t".$backtrace[2]["function"]."\t".
194 substr($query, 0, 2000)."\n", FILE_APPEND);
199 public static function escape($str) {
200 switch (self::$driver) {
202 return substr(@self::$db->quote($str, PDO::PARAM_STR), 1, -1);
204 return @self::$db->real_escape_string($str);
208 public static function connected() {
211 switch (self::$driver) {
213 $r = dba::p("SELECT 1");
214 if (DBM::is_result($r)) {
215 $row = dba::inArray($r);
216 $connected = ($row[0]['1'] == '1');
220 $connected = self::$db->ping();
227 * @brief Replaces ANY_VALUE() function by MIN() function,
228 * if the database server does not support ANY_VALUE().
230 * Considerations for Standard SQL, or MySQL with ONLY_FULL_GROUP_BY (default since 5.7.5).
231 * ANY_VALUE() is available from MySQL 5.7.5 https://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html
232 * A standard fall-back is to use MIN().
234 * @param string $sql An SQL string without the values
235 * @return string The input SQL string modified if necessary.
237 public static function any_value_fallback($sql) {
238 $server_info = self::server_info();
239 if (version_compare($server_info, '5.7.5', '<') ||
240 (stripos($server_info, 'MariaDB') !== false)) {
241 $sql = str_ireplace('ANY_VALUE(', 'MIN(', $sql);
247 * @brief beautifies the query - useful for "SHOW PROCESSLIST"
249 * This is safe when we bind the parameters later.
250 * The parameter values aren't part of the SQL.
252 * @param string $sql An SQL string without the values
253 * @return string The input SQL string modified if necessary.
255 public static function clean_query($sql) {
256 $search = ["\t", "\n", "\r", " "];
257 $replace = [' ', ' ', ' ', ' '];
260 $sql = str_replace($search, $replace, $sql);
261 } while ($oldsql != $sql);
268 * @brief Replaces the ? placeholders with the parameters in the $args array
270 * @param string $sql SQL query
271 * @param array $args The parameters that are to replace the ? placeholders
272 * @return string The replaced SQL query
274 private static function replace_parameters($sql, $args) {
276 foreach ($args AS $param => $value) {
277 if (is_int($args[$param]) || is_float($args[$param])) {
278 $replace = intval($args[$param]);
280 $replace = "'".self::escape($args[$param])."'";
283 $pos = strpos($sql, '?', $offset);
284 if ($pos !== false) {
285 $sql = substr_replace($sql, $replace, $pos, 1);
287 $offset = $pos + strlen($replace);
293 * @brief Convert parameter array to an universal form
294 * @param array $args Parameter array
295 * @return array universalized parameter array
297 private static function getParam($args) {
300 // When the second function parameter is an array then use this as the parameter array
301 if ((count($args) > 0) && (is_array($args[1]))) {
309 * @brief Executes a prepared statement that returns data
310 * @usage Example: $r = p("SELECT * FROM `item` WHERE `guid` = ?", $guid);
312 * Please only use it with complicated queries.
313 * For all regular queries please use dba::select or dba::exists
315 * @param string $sql SQL statement
316 * @return bool|object statement object
318 public static function p($sql) {
321 $stamp1 = microtime(true);
323 $params = self::getParam(func_get_args());
325 // Renumber the array keys to be sure that they fit
328 foreach ($params AS $param) {
329 // Avoid problems with some MySQL servers and boolean values. See issue #3645
330 if (is_bool($param)) {
331 $param = (int)$param;
333 $args[++$i] = $param;
336 if (!self::$connected) {
340 if ((substr_count($sql, '?') != count($args)) && (count($args) > 0)) {
341 // Question: Should we continue or stop the query here?
342 logger('Parameter mismatch. Query "'.$sql.'" - Parameters '.print_r($args, true), LOGGER_DEBUG);
345 $sql = self::clean_query($sql);
346 $sql = self::any_value_fallback($sql);
350 if (x($a->config,'system') && x($a->config['system'], 'db_callstack')) {
351 $sql = "/*".System::callstack()." */ ".$sql;
356 self::$affected_rows = 0;
358 // We have to make some things different if this function is called from "e"
359 $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2);
361 if (isset($trace[1])) {
362 $called_from = $trace[1];
364 // We use just something that is defined to avoid warnings
365 $called_from = $trace[0];
367 // We are having an own error logging in the function "e"
368 $called_from_e = ($called_from['function'] == 'e');
370 switch (self::$driver) {
372 // If there are no arguments we use "query"
373 if (count($args) == 0) {
374 if (!$retval = self::$db->query($sql)) {
375 $errorInfo = self::$db->errorInfo();
376 self::$error = $errorInfo[2];
377 self::$errorno = $errorInfo[1];
381 self::$affected_rows = $retval->rowCount();
385 if (!$stmt = self::$db->prepare($sql)) {
386 $errorInfo = self::$db->errorInfo();
387 self::$error = $errorInfo[2];
388 self::$errorno = $errorInfo[1];
393 foreach ($args AS $param => $value) {
394 $stmt->bindParam($param, $args[$param]);
397 if (!$stmt->execute()) {
398 $errorInfo = $stmt->errorInfo();
399 self::$error = $errorInfo[2];
400 self::$errorno = $errorInfo[1];
404 self::$affected_rows = $retval->rowCount();
408 // There are SQL statements that cannot be executed with a prepared statement
409 $parts = explode(' ', $orig_sql);
410 $command = strtolower($parts[0]);
411 $can_be_prepared = in_array($command, ['select', 'update', 'insert', 'delete']);
413 // The fallback routine is called as well when there are no arguments
414 if (!$can_be_prepared || (count($args) == 0)) {
415 $retval = self::$db->query(self::replace_parameters($sql, $args));
416 if (self::$db->errno) {
417 self::$error = self::$db->error;
418 self::$errorno = self::$db->errno;
421 if (isset($retval->num_rows)) {
422 self::$affected_rows = $retval->num_rows;
424 self::$affected_rows = self::$db->affected_rows;
430 $stmt = self::$db->stmt_init();
432 if (!$stmt->prepare($sql)) {
433 self::$error = $stmt->error;
434 self::$errorno = $stmt->errno;
441 foreach ($args AS $param => $value) {
442 if (is_int($args[$param])) {
444 } elseif (is_float($args[$param])) {
446 } elseif (is_string($args[$param])) {
451 $values[] = &$args[$param];
454 if (count($values) > 0) {
455 array_unshift($values, $params);
456 call_user_func_array([$stmt, 'bind_param'], $values);
459 if (!$stmt->execute()) {
460 self::$error = self::$db->error;
461 self::$errorno = self::$db->errno;
464 $stmt->store_result();
466 self::$affected_rows = $retval->affected_rows;
471 // We are having an own error logging in the function "e"
472 if ((self::$errorno != 0) && !$called_from_e) {
473 // We have to preserve the error code, somewhere in the logging it get lost
474 $error = self::$error;
475 $errorno = self::$errorno;
477 logger('DB Error '.self::$errorno.': '.self::$error."\n".
478 System::callstack(8)."\n".self::replace_parameters($sql, $params));
480 self::$error = $error;
481 self::$errorno = $errorno;
484 $a->save_timestamp($stamp1, 'database');
486 if (x($a->config,'system') && x($a->config['system'], 'db_log')) {
488 $stamp2 = microtime(true);
489 $duration = (float)($stamp2 - $stamp1);
491 if (($duration > $a->config["system"]["db_loglimit"])) {
492 $duration = round($duration, 3);
493 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
495 @file_put_contents($a->config["system"]["db_log"], datetime_convert()."\t".$duration."\t".
496 basename($backtrace[1]["file"])."\t".
497 $backtrace[1]["line"]."\t".$backtrace[2]["function"]."\t".
498 substr(self::replace_parameters($sql, $args), 0, 2000)."\n", FILE_APPEND);
505 * @brief Executes a prepared statement like UPDATE or INSERT that doesn't return data
507 * Please use dba::delete, dba::insert, dba::update, ... instead
509 * @param string $sql SQL statement
510 * @return boolean Was the query successfull? False is returned only if an error occurred
512 public static function e($sql) {
515 $stamp = microtime(true);
517 $params = self::getParam(func_get_args());
519 // In a case of a deadlock we are repeating the query 20 times
523 $stmt = self::p($sql, $params);
525 if (is_bool($stmt)) {
527 } elseif (is_object($stmt)) {
535 } while ((self::$errorno == 1213) && (--$timeout > 0));
537 if (self::$errorno != 0) {
538 // We have to preserve the error code, somewhere in the logging it get lost
539 $error = self::$error;
540 $errorno = self::$errorno;
542 logger('DB Error '.self::$errorno.': '.self::$error."\n".
543 System::callstack(8)."\n".self::replace_parameters($sql, $params));
545 self::$error = $error;
546 self::$errorno = $errorno;
549 $a->save_timestamp($stamp, "database_write");
555 * @brief Check if data exists
557 * @param string $table Table name
558 * @param array $condition array of fields for condition
560 * @return boolean Are there rows for that condition?
562 public static function exists($table, $condition) {
569 $array_element = each($condition);
570 $array_key = $array_element['key'];
571 if (!is_int($array_key)) {
572 $fields = [$array_key];
575 $stmt = self::select($table, $fields, $condition, ['limit' => 1]);
577 if (is_bool($stmt)) {
580 $retval = (self::num_rows($stmt) > 0);
589 * Fetches the first row
591 * Please use dba::selectFirst or dba::exists whenever this is possible.
593 * @brief Fetches the first row
594 * @param string $sql SQL statement
595 * @return array first row of query
597 public static function fetch_first($sql) {
598 $params = self::getParam(func_get_args());
600 $stmt = self::p($sql, $params);
602 if (is_bool($stmt)) {
605 $retval = self::fetch($stmt);
614 * @brief Returns the number of affected rows of the last statement
616 * @return int Number of rows
618 public static function affected_rows() {
619 return self::$affected_rows;
623 * @brief Returns the number of columns of a statement
625 * @param object Statement object
626 * @return int Number of columns
628 public static function columnCount($stmt) {
629 if (!is_object($stmt)) {
632 switch (self::$driver) {
634 return $stmt->columnCount();
636 return $stmt->field_count;
641 * @brief Returns the number of rows of a statement
643 * @param PDOStatement|mysqli_result|mysqli_stmt Statement object
644 * @return int Number of rows
646 public static function num_rows($stmt) {
647 if (!is_object($stmt)) {
650 switch (self::$driver) {
652 return $stmt->rowCount();
654 return $stmt->num_rows;
660 * @brief Fetch a single row
662 * @param mixed $stmt statement object
663 * @return array current row
665 public static function fetch($stmt) {
666 if (!is_object($stmt)) {
670 switch (self::$driver) {
672 return $stmt->fetch(PDO::FETCH_ASSOC);
674 if (get_class($stmt) == 'mysqli_result') {
675 return $stmt->fetch_assoc();
678 // This code works, but is slow
680 // Bind the result to a result array
684 for ($x = 0; $x < $stmt->field_count; $x++) {
685 $cols[] = &$cols_num[$x];
688 call_user_func_array([$stmt, 'bind_result'], $cols);
690 if (!$stmt->fetch()) {
695 // We need to get the field names for the array keys
696 // It seems that there is no better way to do this.
697 $result = $stmt->result_metadata();
698 $fields = $result->fetch_fields();
701 foreach ($cols_num AS $param => $col) {
702 $columns[$fields[$param]->name] = $col;
709 * @brief Insert a row into a table
711 * @param string $table Table name
712 * @param array $param parameter array
713 * @param bool $on_duplicate_update Do an update on a duplicate entry
715 * @return boolean was the insert successfull?
717 public static function insert($table, $param, $on_duplicate_update = false) {
719 if (empty($table) || empty($param)) {
720 logger('Table and fields have to be set');
724 $sql = "INSERT INTO `".self::escape($table)."` (`".implode("`, `", array_keys($param))."`) VALUES (".
725 substr(str_repeat("?, ", count($param)), 0, -2).")";
727 if ($on_duplicate_update) {
728 $sql .= " ON DUPLICATE KEY UPDATE `".implode("` = ?, `", array_keys($param))."` = ?";
730 $values = array_values($param);
731 $param = array_merge_recursive($values, $values);
734 return self::e($sql, $param);
738 * @brief Fetch the id of the last insert command
740 * @return integer Last inserted id
742 public static function lastInsertId() {
743 switch (self::$driver) {
745 $id = self::$db->lastInsertId();
748 $id = self::$db->insert_id;
755 * @brief Locks a table for exclusive write access
757 * This function can be extended in the future to accept a table array as well.
759 * @param string $table Table name
761 * @return boolean was the lock successful?
763 public static function lock($table) {
764 // See here: https://dev.mysql.com/doc/refman/5.7/en/lock-tables-and-transactions.html
765 self::e("SET autocommit=0");
766 $success = self::e("LOCK TABLES `".self::escape($table)."` WRITE");
768 self::e("SET autocommit=1");
770 self::$in_transaction = true;
776 * @brief Unlocks all locked tables
778 * @return boolean was the unlock successful?
780 public static function unlock() {
781 // See here: https://dev.mysql.com/doc/refman/5.7/en/lock-tables-and-transactions.html
783 $success = self::e("UNLOCK TABLES");
784 self::e("SET autocommit=1");
785 self::$in_transaction = false;
790 * @brief Starts a transaction
792 * @return boolean Was the command executed successfully?
794 public static function transaction() {
795 if (!self::e('COMMIT')) {
798 if (!self::e('START TRANSACTION')) {
801 self::$in_transaction = true;
806 * @brief Does a commit
808 * @return boolean Was the command executed successfully?
810 public static function commit() {
811 if (!self::e('COMMIT')) {
814 self::$in_transaction = false;
819 * @brief Does a rollback
821 * @return boolean Was the command executed successfully?
823 public static function rollback() {
824 if (!self::e('ROLLBACK')) {
827 self::$in_transaction = false;
832 * @brief Build the array with the table relations
834 * The array is build from the database definitions in DBStructure.php
836 * This process must only be started once, since the value is cached.
838 private static function build_relation_data() {
839 $definition = DBStructure::definition();
841 foreach ($definition AS $table => $structure) {
842 foreach ($structure['fields'] AS $field => $field_struct) {
843 if (isset($field_struct['relation'])) {
844 foreach ($field_struct['relation'] AS $rel_table => $rel_field) {
845 self::$relation[$rel_table][$rel_field][$table][] = $field;
853 * @brief Delete a row from a table
855 * @param string $table Table name
856 * @param array $conditions Field condition(s)
857 * @param boolean $in_process Internal use: Only do a commit after the last delete
858 * @param array $callstack Internal use: prevent endless loops
860 * @return boolean|array was the delete successful? When $in_process is set: deletion data
862 public static function delete($table, array $conditions, $in_process = false, array &$callstack = [])
864 if (empty($table) || empty($conditions)) {
865 logger('Table and conditions have to be set');
871 // Create a key for the loop prevention
872 $key = $table . ':' . implode(':', array_keys($conditions)) . ':' . implode(':', $conditions);
874 // We quit when this key already exists in the callstack.
875 if (isset($callstack[$key])) {
879 $callstack[$key] = true;
881 $table = self::escape($table);
883 $commands[$key] = ['table' => $table, 'conditions' => $conditions];
885 // To speed up the whole process we cache the table relations
886 if (count(self::$relation) == 0) {
887 self::build_relation_data();
890 // Is there a relation entry for the table?
891 if (isset(self::$relation[$table])) {
892 // We only allow a simple "one field" relation.
893 $field = array_keys(self::$relation[$table])[0];
894 $rel_def = array_values(self::$relation[$table])[0];
896 // Create a key for preventing double queries
897 $qkey = $field . '-' . $table . ':' . implode(':', array_keys($conditions)) . ':' . implode(':', $conditions);
899 // When the search field is the relation field, we don't need to fetch the rows
900 // This is useful when the leading record is already deleted in the frontend but the rest is done in the backend
901 if ((count($conditions) == 1) && ($field == array_keys($conditions)[0])) {
902 foreach ($rel_def AS $rel_table => $rel_fields) {
903 foreach ($rel_fields AS $rel_field) {
904 $retval = self::delete($rel_table, [$rel_field => array_values($conditions)[0]], true, $callstack);
905 $commands = array_merge($commands, $retval);
908 // We quit when this key already exists in the callstack.
909 } elseif (!isset($callstack[$qkey])) {
911 $callstack[$qkey] = true;
913 // Fetch all rows that are to be deleted
914 $data = self::select($table, [$field], $conditions);
916 while ($row = self::fetch($data)) {
917 // Now we accumulate the delete commands
918 $retval = self::delete($table, [$field => $row[$field]], true, $callstack);
919 $commands = array_merge($commands, $retval);
924 // Since we had split the delete command we don't need the original command anymore
925 unset($commands[$key]);
930 // Now we finalize the process
931 $do_transaction = !self::$in_transaction;
933 if ($do_transaction) {
940 foreach ($commands AS $command) {
941 $conditions = $command['conditions'];
942 $array_element = each($conditions);
943 $array_key = $array_element['key'];
944 if (is_int($array_key)) {
945 $condition_string = " WHERE " . array_shift($conditions);
947 $condition_string = " WHERE `" . implode("` = ? AND `", array_keys($conditions)) . "` = ?";
950 if ((count($command['conditions']) > 1) || is_int($array_key)) {
951 $sql = "DELETE FROM `" . $command['table'] . "`" . $condition_string;
952 logger(self::replace_parameters($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::replace_parameters($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 $array_element = each($condition);
1040 $array_key = $array_element['key'];
1041 if (is_int($array_key)) {
1042 $condition_string = " WHERE ".array_shift($condition);
1044 $condition_string = " WHERE `".implode("` = ? AND `", array_keys($condition))."` = ?";
1047 if (is_bool($old_fields)) {
1048 $do_insert = $old_fields;
1050 $old_fields = self::selectFirst($table, [], $condition);
1052 if (is_bool($old_fields)) {
1054 $values = array_merge($condition, $fields);
1055 return self::insert($table, $values, $do_insert);
1061 $do_update = (count($old_fields) == 0);
1063 foreach ($old_fields AS $fieldname => $content) {
1064 if (isset($fields[$fieldname])) {
1065 if ($fields[$fieldname] == $content) {
1066 unset($fields[$fieldname]);
1073 if (!$do_update || (count($fields) == 0)) {
1077 $sql = "UPDATE `".$table."` SET `".
1078 implode("` = ?, `", array_keys($fields))."` = ?".$condition_string;
1080 $params1 = array_values($fields);
1081 $params2 = array_values($condition);
1082 $params = array_merge_recursive($params1, $params2);
1084 return self::e($sql, $params);
1088 * Retrieve a single record from a table and returns it in an associative array
1090 * @brief Retrieve a single record from a table
1091 * @param string $table
1092 * @param array $fields
1093 * @param array $condition
1094 * @param array $params
1095 * @return bool|array
1098 public static function selectFirst($table, array $fields = [], array $condition = [], $params = [])
1100 $params['limit'] = 1;
1101 $result = self::select($table, $fields, $condition, $params);
1103 if (is_bool($result)) {
1106 $row = self::fetch($result);
1107 self::close($result);
1113 * @brief Select rows from a table
1115 * @param string $table Table name
1116 * @param array $fields Array of selected fields, empty for all
1117 * @param array $condition Array of fields for condition
1118 * @param array $params Array of several parameters
1120 * @return boolean|object
1124 * $fields = array("id", "uri", "uid", "network");
1126 * $condition = array("uid" => 1, "network" => 'dspr');
1128 * $condition = array("`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr');
1130 * $params = array("order" => array("id", "received" => true), "limit" => 10);
1132 * $data = dba::select($table, $fields, $condition, $params);
1134 public static function select($table, array $fields = [], array $condition = [], array $params = [])
1140 if (count($fields) > 0) {
1141 $select_fields = "`" . implode("`, `", array_values($fields)) . "`";
1143 $select_fields = "*";
1146 $condition_string = self::buildCondition($condition);
1149 if (isset($params['order'])) {
1150 $order_string = " ORDER BY ";
1151 foreach ($params['order'] AS $fields => $order) {
1152 if (!is_int($fields)) {
1153 $order_string .= "`" . $fields . "` " . ($order ? "DESC" : "ASC") . ", ";
1155 $order_string .= "`" . $order . "`, ";
1158 $order_string = substr($order_string, 0, -2);
1162 if (isset($params['limit']) && is_int($params['limit'])) {
1163 $limit_string = " LIMIT " . $params['limit'];
1166 if (isset($params['limit']) && is_array($params['limit'])) {
1167 $limit_string = " LIMIT " . intval($params['limit'][0]) . ", " . intval($params['limit'][1]);
1170 $sql = "SELECT " . $select_fields . " FROM `" . $table . "`" . $condition_string . $order_string . $limit_string;
1172 $result = self::p($sql, $condition);
1178 * @brief Counts the rows from a table satisfying the provided condition
1180 * @param string $table Table name
1181 * @param array $condition array of fields for condition
1188 * $condition = ["uid" => 1, "network" => 'dspr'];
1190 * $condition = ["`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr'];
1192 * $count = dba::count($table, $condition);
1194 public static function count($table, array $condition = [])
1200 $condition_string = self::buildCondition($condition);
1202 $sql = "SELECT COUNT(*) AS `count` FROM `".$table."`".$condition_string;
1204 $row = self::fetch_first($sql, $condition);
1206 return $row['count'];
1210 * @brief Returns the SQL condition string built from the provided condition array
1212 * This function operates with two modes.
1213 * - Supplied with a filed/value associative array, it builds simple strict
1214 * equality conditions linked by AND.
1215 * - Supplied with a flat list, the first element is the condition string and
1216 * the following arguments are the values to be interpolated
1218 * $condition = ["uid" => 1, "network" => 'dspr'];
1220 * $condition = ["`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr'];
1222 * In either case, the provided array is left with the parameters only
1224 * @param array $condition
1227 private static function buildCondition(array &$condition = [])
1229 $condition_string = '';
1230 if (count($condition) > 0) {
1231 $array_element = each($condition);
1232 $array_key = $array_element['key'];
1233 if (is_int($array_key)) {
1234 $condition_string = " WHERE ".array_shift($condition);
1236 $condition_string = " WHERE `".implode("` = ? AND `", array_keys($condition))."` = ?";
1240 return $condition_string;
1244 * @brief Fills an array with data from a query
1246 * @param object $stmt statement object
1247 * @return array Data array
1249 public static function inArray($stmt, $do_close = true) {
1250 if (is_bool($stmt)) {
1255 while ($row = self::fetch($stmt)) {
1265 * @brief Returns the error number of the last query
1267 * @return string Error number (0 if no error)
1269 public static function errorNo() {
1270 return self::$errorno;
1274 * @brief Returns the error message of the last query
1276 * @return string Error message ('' if no error)
1278 public static function errorMessage() {
1279 return self::$error;
1283 * @brief Closes the current statement
1285 * @param object $stmt statement object
1286 * @return boolean was the close successful?
1288 public static function close($stmt) {
1289 if (!is_object($stmt)) {
1293 switch (self::$driver) {
1295 return $stmt->closeCursor();
1297 $stmt->free_result();
1298 return $stmt->close();
1303 function dbesc($str) {
1304 if (dba::$connected) {
1305 return(dba::escape($str));
1307 return(str_replace("'","\\'",$str));
1312 * @brief execute SQL query with printf style args - deprecated
1314 * Please use the dba:: functions instead:
1315 * dba::select, dba::exists, dba::insert
1316 * dba::delete, dba::update, dba::p, dba::e
1318 * @param $args Query parameters (1 to N parameters of different types)
1319 * @return array|bool Query array
1322 $args = func_get_args();
1325 if (!dba::$connected) {
1329 $sql = dba::clean_query($sql);
1330 $sql = dba::any_value_fallback($sql);
1332 $stmt = @vsprintf($sql, $args);
1334 $ret = dba::p($stmt);
1336 if (is_bool($ret)) {
1340 $columns = dba::columnCount($ret);
1342 $data = dba::inArray($ret);
1344 if ((count($data) == 0) && ($columns == 0)) {
1351 function dba_timer() {
1352 return microtime(true);