2 use \Friendica\Core\System;
4 require_once("dbm.php");
5 require_once('include/datetime.php');
8 * @class MySQL database class
10 * This class is for the low level database stuff that does driver specific things.
19 public $connected = false;
20 public $error = false;
22 public $affected_rows = 0;
23 private $_server_info = '';
24 private static $in_transaction = false;
26 private static $relation = array();
28 function __construct($serveraddr, $user, $pass, $db, $install = false) {
31 $stamp1 = microtime(true);
33 $serveraddr = trim($serveraddr);
35 $serverdata = explode(':', $serveraddr);
36 $server = $serverdata[0];
38 if (count($serverdata) > 1) {
39 $port = trim($serverdata[1]);
42 $server = trim($server);
47 if (!(strlen($server) && strlen($user))) {
48 $this->connected = false;
54 if (strlen($server) && ($server !== 'localhost') && ($server !== '127.0.0.1')) {
55 if (! dns_get_record($server, DNS_A + DNS_CNAME + DNS_PTR)) {
56 $this->error = sprintf(t('Cannot locate DNS info for database server \'%s\''), $server);
57 $this->connected = false;
64 if (class_exists('\PDO') && in_array('mysql', PDO::getAvailableDrivers())) {
65 $this->driver = 'pdo';
66 $connect = "mysql:host=".$server.";dbname=".$db;
69 $connect .= ";port=".$port;
72 if (isset($a->config["system"]["db_charset"])) {
73 $connect .= ";charset=".$a->config["system"]["db_charset"];
76 $this->db = @new PDO($connect, $user, $pass);
77 $this->connected = true;
78 } catch (PDOException $e) {
79 $this->connected = false;
83 if (!$this->connected && class_exists('mysqli')) {
84 $this->driver = 'mysqli';
85 $this->db = @new mysqli($server, $user, $pass, $db, $port);
86 if (!mysqli_connect_errno()) {
87 $this->connected = true;
89 if (isset($a->config["system"]["db_charset"])) {
90 $this->db->set_charset($a->config["system"]["db_charset"]);
95 if (!$this->connected && function_exists('mysql_connect')) {
96 $this->driver = 'mysql';
97 $this->db = mysql_connect($serveraddr, $user, $pass);
98 if ($this->db && mysql_select_db($db, $this->db)) {
99 $this->connected = true;
101 if (isset($a->config["system"]["db_charset"])) {
102 mysql_set_charset($a->config["system"]["db_charset"], $this->db);
107 // No suitable SQL driver was found.
108 if (!$this->connected) {
111 system_unavailable();
114 $a->save_timestamp($stamp1, "network");
120 * @brief Returns the MySQL server version string
122 * This function discriminate between the deprecated mysql API and the current
123 * object-oriented mysqli API. Example of returned string: 5.5.46-0+deb8u1
127 public function server_info() {
128 if ($this->_server_info == '') {
129 switch ($this->driver) {
131 $this->_server_info = $this->db->getAttribute(PDO::ATTR_SERVER_VERSION);
134 $this->_server_info = $this->db->server_info;
137 $this->_server_info = mysql_get_server_info($this->db);
141 return $this->_server_info;
145 * @brief Returns the selected database name
149 public function database_name() {
150 $r = $this->q("SELECT DATABASE() AS `db`");
156 * @brief Analyze a database query and log this if some conditions are met.
158 * @param string $query The database query that will be analyzed
160 public function log_index($query) {
163 if (empty($a->config["system"]["db_log_index"])) {
167 // Don't explain an explain statement
168 if (strtolower(substr($query, 0, 7)) == "explain") {
172 // Only do the explain on "select", "update" and "delete"
173 if (!in_array(strtolower(substr($query, 0, 6)), array("select", "update", "delete"))) {
177 $r = $this->q("EXPLAIN ".$query);
178 if (!dbm::is_result($r)) {
182 $watchlist = explode(',', $a->config["system"]["db_log_index_watch"]);
183 $blacklist = explode(',', $a->config["system"]["db_log_index_blacklist"]);
185 foreach ($r AS $row) {
186 if ((intval($a->config["system"]["db_loglimit_index"]) > 0)) {
187 $log = (in_array($row['key'], $watchlist) &&
188 ($row['rows'] >= intval($a->config["system"]["db_loglimit_index"])));
193 if ((intval($a->config["system"]["db_loglimit_index_high"]) > 0) && ($row['rows'] >= intval($a->config["system"]["db_loglimit_index_high"]))) {
197 if (in_array($row['key'], $blacklist) || ($row['key'] == "")) {
202 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
203 @file_put_contents($a->config["system"]["db_log_index"], datetime_convert()."\t".
204 $row['key']."\t".$row['rows']."\t".$row['Extra']."\t".
205 basename($backtrace[1]["file"])."\t".
206 $backtrace[1]["line"]."\t".$backtrace[2]["function"]."\t".
207 substr($query, 0, 2000)."\n", FILE_APPEND);
213 * @brief execute SQL query - deprecated
215 * Please use the dba:: functions instead:
216 * dba::select, dba::exists, dba::insert
217 * dba::delete, dba::update, dba::p, dba::e
219 * @param string $sql SQL query
220 * @return array Query array
222 public function q($sql) {
223 $ret = self::p($sql);
229 $columns = self::columnCount($ret);
231 $data = self::inArray($ret);
233 if ((count($data) == 0) && ($columns == 0)) {
240 public function escape($str) {
241 if ($this->db && $this->connected) {
242 switch ($this->driver) {
244 return substr(@$this->db->quote($str, PDO::PARAM_STR), 1, -1);
246 return @$this->db->real_escape_string($str);
248 return @mysql_real_escape_string($str,$this->db);
253 function connected() {
254 switch ($this->driver) {
256 // Not sure if this really is working like expected
257 $connected = ($this->db->getAttribute(PDO::ATTR_CONNECTION_STATUS) != "");
260 $connected = $this->db->ping();
263 $connected = mysql_ping($this->db);
269 function __destruct() {
271 switch ($this->driver) {
279 mysql_close($this->db);
286 * @brief Replaces ANY_VALUE() function by MIN() function,
287 * if the database server does not support ANY_VALUE().
289 * Considerations for Standard SQL, or MySQL with ONLY_FULL_GROUP_BY (default since 5.7.5).
290 * ANY_VALUE() is available from MySQL 5.7.5 https://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html
291 * A standard fall-back is to use MIN().
293 * @param string $sql An SQL string without the values
294 * @return string The input SQL string modified if necessary.
296 public function any_value_fallback($sql) {
297 $server_info = $this->server_info();
298 if (version_compare($server_info, '5.7.5', '<') ||
299 (stripos($server_info, 'MariaDB') !== false)) {
300 $sql = str_ireplace('ANY_VALUE(', 'MIN(', $sql);
306 * @brief beautifies the query - useful for "SHOW PROCESSLIST"
308 * This is safe when we bind the parameters later.
309 * The parameter values aren't part of the SQL.
311 * @param string $sql An SQL string without the values
312 * @return string The input SQL string modified if necessary.
314 public function clean_query($sql) {
315 $search = array("\t", "\n", "\r", " ");
316 $replace = array(' ', ' ', ' ', ' ');
319 $sql = str_replace($search, $replace, $sql);
320 } while ($oldsql != $sql);
327 * @brief Replaces the ? placeholders with the parameters in the $args array
329 * @param string $sql SQL query
330 * @param array $args The parameters that are to replace the ? placeholders
331 * @return string The replaced SQL query
333 private static function replace_parameters($sql, $args) {
335 foreach ($args AS $param => $value) {
336 if (is_int($args[$param]) || is_float($args[$param])) {
337 $replace = intval($args[$param]);
339 $replace = "'".self::$dbo->escape($args[$param])."'";
342 $pos = strpos($sql, '?', $offset);
343 if ($pos !== false) {
344 $sql = substr_replace($sql, $replace, $pos, 1);
346 $offset = $pos + strlen($replace);
352 * @brief Convert parameter array to an universal form
353 * @param array $args Parameter array
354 * @return array universalized parameter array
356 private static function getParam($args) {
359 // When the second function parameter is an array then use this as the parameter array
360 if ((count($args) > 0) && (is_array($args[1]))) {
368 * @brief Executes a prepared statement that returns data
369 * @usage Example: $r = p("SELECT * FROM `item` WHERE `guid` = ?", $guid);
371 * Please only use it with complicated queries.
372 * For all regular queries please use dba::select or dba::exists
374 * @param string $sql SQL statement
375 * @return object statement object
377 public static function p($sql) {
380 $stamp1 = microtime(true);
382 $params = self::getParam(func_get_args());
384 // Renumber the array keys to be sure that they fit
387 foreach ($params AS $param) {
388 // Avoid problems with some MySQL servers and boolean values. See issue #3645
389 if (is_bool($param)) {
390 $param = (int)$param;
392 $args[++$i] = $param;
395 if (!self::$dbo || !self::$dbo->connected) {
399 if ((substr_count($sql, '?') != count($args)) && (count($args) > 0)) {
400 // Question: Should we continue or stop the query here?
401 logger('Parameter mismatch. Query "'.$sql.'" - Parameters '.print_r($args, true), LOGGER_DEBUG);
404 $sql = self::$dbo->clean_query($sql);
405 $sql = self::$dbo->any_value_fallback($sql);
409 if (x($a->config,'system') && x($a->config['system'], 'db_callstack')) {
410 $sql = "/*".System::callstack()." */ ".$sql;
413 self::$dbo->error = '';
414 self::$dbo->errorno = 0;
415 self::$dbo->affected_rows = 0;
417 // We have to make some things different if this function is called from "e"
418 $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2);
420 if (isset($trace[1])) {
421 $called_from = $trace[1];
423 // We use just something that is defined to avoid warnings
424 $called_from = $trace[0];
426 // We are having an own error logging in the function "e"
427 $called_from_e = ($called_from['function'] == 'e');
429 switch (self::$dbo->driver) {
431 // If there are no arguments we use "query"
432 if (count($args) == 0) {
433 if (!$retval = self::$dbo->db->query($sql)) {
434 $errorInfo = self::$dbo->db->errorInfo();
435 self::$dbo->error = $errorInfo[2];
436 self::$dbo->errorno = $errorInfo[1];
440 self::$dbo->affected_rows = $retval->rowCount();
444 if (!$stmt = self::$dbo->db->prepare($sql)) {
445 $errorInfo = self::$dbo->db->errorInfo();
446 self::$dbo->error = $errorInfo[2];
447 self::$dbo->errorno = $errorInfo[1];
452 foreach ($args AS $param => $value) {
453 $stmt->bindParam($param, $args[$param]);
456 if (!$stmt->execute()) {
457 $errorInfo = $stmt->errorInfo();
458 self::$dbo->error = $errorInfo[2];
459 self::$dbo->errorno = $errorInfo[1];
463 self::$dbo->affected_rows = $retval->rowCount();
467 // There are SQL statements that cannot be executed with a prepared statement
468 $parts = explode(' ', $orig_sql);
469 $command = strtolower($parts[0]);
470 $can_be_prepared = in_array($command, array('select', 'update', 'insert', 'delete'));
472 // The fallback routine is called as well when there are no arguments
473 if (!$can_be_prepared || (count($args) == 0)) {
474 $retval = self::$dbo->db->query(self::replace_parameters($sql, $args));
475 if (self::$dbo->db->errno) {
476 self::$dbo->error = self::$dbo->db->error;
477 self::$dbo->errorno = self::$dbo->db->errno;
480 if (isset($retval->num_rows)) {
481 self::$dbo->affected_rows = $retval->num_rows;
483 self::$dbo->affected_rows = self::$dbo->db->affected_rows;
489 $stmt = self::$dbo->db->stmt_init();
491 if (!$stmt->prepare($sql)) {
492 self::$dbo->error = $stmt->error;
493 self::$dbo->errorno = $stmt->errno;
500 foreach ($args AS $param => $value) {
501 if (is_int($args[$param])) {
503 } elseif (is_float($args[$param])) {
505 } elseif (is_string($args[$param])) {
510 $values[] = &$args[$param];
513 if (count($values) > 0) {
514 array_unshift($values, $params);
515 call_user_func_array(array($stmt, 'bind_param'), $values);
518 if (!$stmt->execute()) {
519 self::$dbo->error = self::$dbo->db->error;
520 self::$dbo->errorno = self::$dbo->db->errno;
523 $stmt->store_result();
525 self::$dbo->affected_rows = $retval->affected_rows;
529 // For the old "mysql" functions we cannot use prepared statements
530 $retval = mysql_query(self::replace_parameters($sql, $args), self::$dbo->db);
531 if (mysql_errno(self::$dbo->db)) {
532 self::$dbo->error = mysql_error(self::$dbo->db);
533 self::$dbo->errorno = mysql_errno(self::$dbo->db);
535 self::$dbo->affected_rows = mysql_affected_rows($retval);
537 // Due to missing mysql_* support this here wasn't tested at all
538 // See here: http://php.net/manual/en/function.mysql-num-rows.php
539 if (self::$dbo->affected_rows <= 0) {
540 self::$dbo->affected_rows = mysql_num_rows($retval);
546 // We are having an own error logging in the function "e"
547 if ((self::$dbo->errorno != 0) && !$called_from_e) {
548 // We have to preserve the error code, somewhere in the logging it get lost
549 $error = self::$dbo->error;
550 $errorno = self::$dbo->errorno;
552 logger('DB Error '.self::$dbo->errorno.': '.self::$dbo->error."\n".
553 System::callstack(8)."\n".self::replace_parameters($sql, $params));
555 self::$dbo->error = $error;
556 self::$dbo->errorno = $errorno;
559 $a->save_timestamp($stamp1, 'database');
561 if (x($a->config,'system') && x($a->config['system'], 'db_log')) {
563 $stamp2 = microtime(true);
564 $duration = (float)($stamp2 - $stamp1);
566 if (($duration > $a->config["system"]["db_loglimit"])) {
567 $duration = round($duration, 3);
568 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
570 @file_put_contents($a->config["system"]["db_log"], datetime_convert()."\t".$duration."\t".
571 basename($backtrace[1]["file"])."\t".
572 $backtrace[1]["line"]."\t".$backtrace[2]["function"]."\t".
573 substr(self::replace_parameters($sql, $args), 0, 2000)."\n", FILE_APPEND);
580 * @brief Executes a prepared statement like UPDATE or INSERT that doesn't return data
582 * Please use dba::delete, dba::insert, dba::update, ... instead
584 * @param string $sql SQL statement
585 * @return boolean Was the query successfull? False is returned only if an error occurred
587 public static function e($sql) {
590 $stamp = microtime(true);
592 $params = self::getParam(func_get_args());
594 // In a case of a deadlock we are repeating the query 20 times
598 $stmt = self::p($sql, $params);
600 if (is_bool($stmt)) {
602 } elseif (is_object($stmt)) {
610 } while ((self::$dbo->errorno == 1213) && (--$timeout > 0));
612 if (self::$dbo->errorno != 0) {
613 // We have to preserve the error code, somewhere in the logging it get lost
614 $error = self::$dbo->error;
615 $errorno = self::$dbo->errorno;
617 logger('DB Error '.self::$dbo->errorno.': '.self::$dbo->error."\n".
618 System::callstack(8)."\n".self::replace_parameters($sql, $params));
620 self::$dbo->error = $error;
621 self::$dbo->errorno = $errorno;
624 $a->save_timestamp($stamp, "database_write");
630 * @brief Check if data exists
632 * @param string $table Table name
633 * @param array $condition array of fields for condition
635 * @return boolean Are there rows for that condition?
637 public static function exists($table, $condition) {
644 $array_element = each($condition);
645 $array_key = $array_element['key'];
646 if (!is_int($array_key)) {
647 $fields = array($array_key);
650 $stmt = self::select($table, $fields, $condition, array('limit' => 1, 'only_query' => true));
652 if (is_bool($stmt)) {
655 $retval = (self::num_rows($stmt) > 0);
664 * @brief Fetches the first row
666 * Please use dba::select or dba::exists whenever this is possible.
668 * @param string $sql SQL statement
669 * @return array first row of query
671 public static function fetch_first($sql) {
672 $params = self::getParam(func_get_args());
674 $stmt = self::p($sql, $params);
676 if (is_bool($stmt)) {
679 $retval = self::fetch($stmt);
688 * @brief Returns the number of affected rows of the last statement
690 * @return int Number of rows
692 public static function affected_rows() {
693 return self::$dbo->affected_rows;
697 * @brief Returns the number of columns of a statement
699 * @param object Statement object
700 * @return int Number of columns
702 public static function columnCount($stmt) {
703 if (!is_object($stmt)) {
706 switch (self::$dbo->driver) {
708 return $stmt->columnCount();
710 return $stmt->field_count;
712 return mysql_affected_rows($stmt);
717 * @brief Returns the number of rows of a statement
719 * @param object Statement object
720 * @return int Number of rows
722 public static function num_rows($stmt) {
723 if (!is_object($stmt)) {
726 switch (self::$dbo->driver) {
728 return $stmt->rowCount();
730 return $stmt->num_rows;
732 return mysql_num_rows($stmt);
738 * @brief Fetch a single row
740 * @param object $stmt statement object
741 * @return array current row
743 public static function fetch($stmt) {
744 if (!is_object($stmt)) {
748 switch (self::$dbo->driver) {
750 return $stmt->fetch(PDO::FETCH_ASSOC);
752 if (get_class($stmt) == 'mysqli_result') {
753 return $stmt->fetch_assoc();
756 // This code works, but is slow
758 // Bind the result to a result array
762 for ($x = 0; $x < $stmt->field_count; $x++) {
763 $cols[] = &$cols_num[$x];
766 call_user_func_array(array($stmt, 'bind_result'), $cols);
768 if (!$stmt->fetch()) {
773 // We need to get the field names for the array keys
774 // It seems that there is no better way to do this.
775 $result = $stmt->result_metadata();
776 $fields = $result->fetch_fields();
779 foreach ($cols_num AS $param => $col) {
780 $columns[$fields[$param]->name] = $col;
784 return mysql_fetch_array(self::$dbo->result, MYSQL_ASSOC);
789 * @brief Insert a row into a table
791 * @param string $table Table name
792 * @param array $param parameter array
793 * @param bool $on_duplicate_update Do an update on a duplicate entry
795 * @return boolean was the insert successfull?
797 public static function insert($table, $param, $on_duplicate_update = false) {
798 $sql = "INSERT INTO `".self::$dbo->escape($table)."` (`".implode("`, `", array_keys($param))."`) VALUES (".
799 substr(str_repeat("?, ", count($param)), 0, -2).")";
801 if ($on_duplicate_update) {
802 $sql .= " ON DUPLICATE KEY UPDATE `".implode("` = ?, `", array_keys($param))."` = ?";
804 $values = array_values($param);
805 $param = array_merge_recursive($values, $values);
808 return self::e($sql, $param);
812 * @brief Fetch the id of the last insert command
814 * @return integer Last inserted id
816 public static function lastInsertId() {
817 switch (self::$dbo->driver) {
819 $id = self::$dbo->db->lastInsertId();
822 $id = self::$dbo->db->insert_id;
825 $id = mysql_insert_id(self::$dbo);
832 * @brief Locks a table for exclusive write access
834 * This function can be extended in the future to accept a table array as well.
836 * @param string $table Table name
838 * @return boolean was the lock successful?
840 public static function lock($table) {
841 // See here: https://dev.mysql.com/doc/refman/5.7/en/lock-tables-and-transactions.html
842 self::e("SET autocommit=0");
843 $success = self::e("LOCK TABLES `".self::$dbo->escape($table)."` WRITE");
845 self::e("SET autocommit=1");
847 self::$in_transaction = true;
853 * @brief Unlocks all locked tables
855 * @return boolean was the unlock successful?
857 public static function unlock() {
858 // See here: https://dev.mysql.com/doc/refman/5.7/en/lock-tables-and-transactions.html
860 $success = self::e("UNLOCK TABLES");
861 self::e("SET autocommit=1");
862 self::$in_transaction = false;
867 * @brief Starts a transaction
869 * @return boolean Was the command executed successfully?
871 public static function transaction() {
872 if (!self::e('COMMIT')) {
875 if (!self::e('START TRANSACTION')) {
878 self::$in_transaction = true;
883 * @brief Does a commit
885 * @return boolean Was the command executed successfully?
887 public static function commit() {
888 if (!self::e('COMMIT')) {
891 self::$in_transaction = false;
896 * @brief Does a rollback
898 * @return boolean Was the command executed successfully?
900 public static function rollback() {
901 if (!self::e('ROLLBACK')) {
904 self::$in_transaction = false;
909 * @brief Build the array with the table relations
911 * The array is build from the database definitions in dbstructure.php
913 * This process must only be started once, since the value is cached.
915 private static function build_relation_data() {
916 $definition = db_definition();
918 foreach ($definition AS $table => $structure) {
919 foreach ($structure['fields'] AS $field => $field_struct) {
920 if (isset($field_struct['relation'])) {
921 foreach ($field_struct['relation'] AS $rel_table => $rel_field) {
922 self::$relation[$rel_table][$rel_field][$table][] = $field;
930 * @brief Delete a row from a table
932 * @param string $table Table name
933 * @param array $param parameter array
934 * @param boolean $in_process Internal use: Only do a commit after the last delete
935 * @param array $callstack Internal use: prevent endless loops
937 * @return boolean|array was the delete successfull? When $in_process is set: deletion data
939 public static function delete($table, $param, $in_process = false, &$callstack = array()) {
943 // Create a key for the loop prevention
944 $key = $table.':'.implode(':', array_keys($param)).':'.implode(':', $param);
946 // We quit when this key already exists in the callstack.
947 if (isset($callstack[$key])) {
951 $callstack[$key] = true;
953 $table = self::$dbo->escape($table);
955 $commands[$key] = array('table' => $table, 'param' => $param);
957 // To speed up the whole process we cache the table relations
958 if (count(self::$relation) == 0) {
959 self::build_relation_data();
962 // Is there a relation entry for the table?
963 if (isset(self::$relation[$table])) {
964 // We only allow a simple "one field" relation.
965 $field = array_keys(self::$relation[$table])[0];
966 $rel_def = array_values(self::$relation[$table])[0];
968 // Create a key for preventing double queries
969 $qkey = $field.'-'.$table.':'.implode(':', array_keys($param)).':'.implode(':', $param);
971 // When the search field is the relation field, we don't need to fetch the rows
972 // This is useful when the leading record is already deleted in the frontend but the rest is done in the backend
973 if ((count($param) == 1) && ($field == array_keys($param)[0])) {
974 foreach ($rel_def AS $rel_table => $rel_fields) {
975 foreach ($rel_fields AS $rel_field) {
976 $retval = self::delete($rel_table, array($rel_field => array_values($param)[0]), true, $callstack);
977 $commands = array_merge($commands, $retval);
980 // We quit when this key already exists in the callstack.
981 } elseif (!isset($callstack[$qkey])) {
983 $callstack[$qkey] = true;
985 // Fetch all rows that are to be deleted
986 $data = self::select($table, array($field), $param);
988 while ($row = self::fetch($data)) {
989 // Now we accumulate the delete commands
990 $retval = self::delete($table, array($field => $row[$field]), true, $callstack);
991 $commands = array_merge($commands, $retval);
996 // Since we had split the delete command we don't need the original command anymore
997 unset($commands[$key]);
1002 // Now we finalize the process
1003 $do_transaction = !self::$in_transaction;
1005 if ($do_transaction) {
1006 self::transaction();
1009 $compacted = array();
1012 foreach ($commands AS $command) {
1013 $condition = $command['param'];
1014 $array_element = each($condition);
1015 $array_key = $array_element['key'];
1016 if (is_int($array_key)) {
1017 $condition_string = " WHERE ".array_shift($condition);
1019 $condition_string = " WHERE `".implode("` = ? AND `", array_keys($condition))."` = ?";
1022 if ((count($command['param']) > 1) || is_int($array_key)) {
1023 $sql = "DELETE FROM `".$command['table']."`".$condition_string;
1024 logger(self::replace_parameters($sql, $condition), LOGGER_DATA);
1026 if (!self::e($sql, $condition)) {
1027 if ($do_transaction) {
1033 $key_table = $command['table'];
1034 $key_param = array_keys($command['param'])[0];
1035 $value = array_values($command['param'])[0];
1037 // Split the SQL queries in chunks of 100 values
1038 // We do the $i stuff here to make the code better readable
1039 $i = $counter[$key_table][$key_param];
1040 if (count($compacted[$key_table][$key_param][$i]) > 100) {
1044 $compacted[$key_table][$key_param][$i][$value] = $value;
1045 $counter[$key_table][$key_param] = $i;
1048 foreach ($compacted AS $table => $values) {
1049 foreach ($values AS $field => $field_value_list) {
1050 foreach ($field_value_list AS $field_values) {
1051 $sql = "DELETE FROM `".$table."` WHERE `".$field."` IN (".
1052 substr(str_repeat("?, ", count($field_values)), 0, -2).");";
1054 logger(self::replace_parameters($sql, $field_values), LOGGER_DATA);
1056 if (!self::e($sql, $field_values)) {
1057 if ($do_transaction) {
1065 if ($do_transaction) {
1075 * @brief Updates rows
1077 * Updates rows in the database. When $old_fields is set to an array,
1078 * the system will only do an update if the fields in that array changed.
1081 * Only the values in $old_fields are compared.
1082 * This is an intentional behaviour.
1085 * We include the timestamp field in $fields but not in $old_fields.
1086 * Then the row will only get the new timestamp when the other fields had changed.
1088 * When $old_fields is set to a boolean value the system will do this compare itself.
1089 * When $old_fields is set to "true" the system will do an insert if the row doesn't exists.
1092 * Only set $old_fields to a boolean value when you are sure that you will update a single row.
1093 * When you set $old_fields to "true" then $fields must contain all relevant fields!
1095 * @param string $table Table name
1096 * @param array $fields contains the fields that are updated
1097 * @param array $condition condition array with the key values
1098 * @param array|boolean $old_fields array with the old field values that are about to be replaced (true = update on duplicate)
1100 * @return boolean was the update successfull?
1102 public static function update($table, $fields, $condition, $old_fields = array()) {
1104 $table = self::$dbo->escape($table);
1106 if (count($condition) > 0) {
1107 $array_element = each($condition);
1108 $array_key = $array_element['key'];
1109 if (is_int($array_key)) {
1110 $condition_string = " WHERE ".array_shift($condition);
1112 $condition_string = " WHERE `".implode("` = ? AND `", array_keys($condition))."` = ?";
1115 $condition_string = "";
1118 if (is_bool($old_fields)) {
1119 $do_insert = $old_fields;
1121 $old_fields = self::select($table, array(), $condition, array('limit' => 1));
1123 if (is_bool($old_fields)) {
1125 $values = array_merge($condition, $fields);
1126 return self::insert($table, $values, $do_insert);
1128 $old_fields = array();
1132 $do_update = (count($old_fields) == 0);
1134 foreach ($old_fields AS $fieldname => $content) {
1135 if (isset($fields[$fieldname])) {
1136 if ($fields[$fieldname] == $content) {
1137 unset($fields[$fieldname]);
1144 if (!$do_update || (count($fields) == 0)) {
1148 $sql = "UPDATE `".$table."` SET `".
1149 implode("` = ?, `", array_keys($fields))."` = ?".$condition_string;
1151 $params1 = array_values($fields);
1152 $params2 = array_values($condition);
1153 $params = array_merge_recursive($params1, $params2);
1155 return self::e($sql, $params);
1159 * @brief Select rows from a table
1161 * @param string $table Table name
1162 * @param array $fields array of selected fields
1163 * @param array $condition array of fields for condition
1164 * @param array $params array of several parameters
1166 * @return boolean|object If "limit" is equal "1" only a single row is returned, else a query object is returned
1170 * $fields = array("id", "uri", "uid", "network");
1172 * $condition = array("uid" => 1, "network" => 'dspr');
1174 * $condition = array("`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr');
1176 * $params = array("order" => array("id", "received" => true), "limit" => 1);
1178 * $data = dba::select($table, $fields, $condition, $params);
1180 public static function select($table, $fields = array(), $condition = array(), $params = array()) {
1185 if (count($fields) > 0) {
1186 $select_fields = "`".implode("`, `", array_values($fields))."`";
1188 $select_fields = "*";
1191 if (count($condition) > 0) {
1192 $array_element = each($condition);
1193 $array_key = $array_element['key'];
1194 if (is_int($array_key)) {
1195 $condition_string = " WHERE ".array_shift($condition);
1197 $condition_string = " WHERE `".implode("` = ? AND `", array_keys($condition))."` = ?";
1200 $condition_string = "";
1204 $single_row = false;
1206 if (isset($params['order'])) {
1207 $param_string .= " ORDER BY ";
1208 foreach ($params['order'] AS $fields => $order) {
1209 if (!is_int($fields)) {
1210 $param_string .= "`".$fields."` ".($order ? "DESC" : "ASC").", ";
1212 $param_string .= "`".$order."`, ";
1215 $param_string = substr($param_string, 0, -2);
1218 if (isset($params['limit']) && is_int($params['limit'])) {
1219 $param_string .= " LIMIT ".$params['limit'];
1220 $single_row = ($params['limit'] == 1);
1223 if (isset($params['only_query']) && $params['only_query']) {
1224 $single_row = !$params['only_query'];
1227 $sql = "SELECT ".$select_fields." FROM `".$table."`".$condition_string.$param_string;
1229 $result = self::p($sql, $condition);
1231 if (is_bool($result) || !$single_row) {
1234 $row = self::fetch($result);
1235 self::close($result);
1242 * @brief Fills an array with data from a query
1244 * @param object $stmt statement object
1245 * @return array Data array
1247 public static function inArray($stmt, $do_close = true) {
1248 if (is_bool($stmt)) {
1253 while ($row = self::fetch($stmt)) {
1263 * @brief Returns the error number of the last query
1265 * @return string Error number (0 if no error)
1267 public static function errorNo() {
1268 return self::$dbo->errorno;
1272 * @brief Returns the error message of the last query
1274 * @return string Error message ('' if no error)
1276 public static function errorMessage() {
1277 return self::$dbo->error;
1281 * @brief Closes the current statement
1283 * @param object $stmt statement object
1284 * @return boolean was the close successfull?
1286 public static function close($stmt) {
1287 if (!is_object($stmt)) {
1291 switch (self::$dbo->driver) {
1293 return $stmt->closeCursor();
1295 return $stmt->free_result();
1296 return $stmt->close();
1298 return mysql_free_result($stmt);
1303 function dbesc($str) {
1306 if ($db && $db->connected) {
1307 return($db->escape($str));
1309 return(str_replace("'","\\'",$str));
1314 * @brief execute SQL query with printf style args - deprecated
1316 * Please use the dba:: functions instead:
1317 * dba::select, dba::exists, dba::insert
1318 * dba::delete, dba::update, dba::p, dba::e
1320 * @param $args Query parameters (1 to N parameters of different types)
1321 * @return array Query array
1326 $args = func_get_args();
1329 if (!$db || !$db->connected) {
1333 $sql = $db->clean_query($sql);
1334 $sql = $db->any_value_fallback($sql);
1336 $stmt = @vsprintf($sql, $args);
1338 $ret = dba::p($stmt);
1340 if (is_bool($ret)) {
1344 $columns = dba::columnCount($ret);
1346 $data = dba::inArray($ret);
1348 if ((count($data) == 0) && ($columns == 0)) {
1355 function dba_timer() {
1356 return microtime(true);