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.
14 public static $connected = true;
16 private static $_server_info = '';
18 private static $driver;
19 private static $error = false;
20 private static $errorno = 0;
21 private static $affected_rows = 0;
22 private static $in_transaction = false;
23 private static $relation = array();
25 public static function connect($serveraddr, $user, $pass, $db, $install = false) {
26 if (!is_null(self::$db)) {
32 $stamp1 = microtime(true);
34 $serveraddr = trim($serveraddr);
36 $serverdata = explode(':', $serveraddr);
37 $server = $serverdata[0];
39 if (count($serverdata) > 1) {
40 $port = trim($serverdata[1]);
43 $server = trim($server);
48 if (!(strlen($server) && strlen($user))) {
49 self::$connected = false;
55 if (strlen($server) && ($server !== 'localhost') && ($server !== '127.0.0.1')) {
56 if (! dns_get_record($server, DNS_A + DNS_CNAME + DNS_PTR)) {
57 self::$error = sprintf(t('Cannot locate DNS info for database server \'%s\''), $server);
58 self::$connected = false;
65 if (class_exists('\PDO') && in_array('mysql', PDO::getAvailableDrivers())) {
66 self::$driver = 'pdo';
67 $connect = "mysql:host=".$server.";dbname=".$db;
70 $connect .= ";port=".$port;
73 if (isset($a->config["system"]["db_charset"])) {
74 $connect .= ";charset=".$a->config["system"]["db_charset"];
77 self::$db = @new PDO($connect, $user, $pass);
78 self::$connected = true;
79 } catch (PDOException $e) {
80 self::$connected = false;
84 if (!self::$connected && class_exists('mysqli')) {
85 self::$driver = 'mysqli';
86 self::$db = @new mysqli($server, $user, $pass, $db, $port);
87 if (!mysqli_connect_errno()) {
88 self::$connected = true;
90 if (isset($a->config["system"]["db_charset"])) {
91 self::$db->set_charset($a->config["system"]["db_charset"]);
96 if (!self::$connected && function_exists('mysql_connect')) {
97 self::$driver = 'mysql';
98 self::$db = mysql_connect($serveraddr, $user, $pass);
99 if (self::$db && mysql_select_db($db, self::$db)) {
100 self::$connected = true;
102 if (isset($a->config["system"]["db_charset"])) {
103 mysql_set_charset($a->config["system"]["db_charset"], self::$db);
108 // No suitable SQL driver was found.
109 if (!self::$connected) {
112 system_unavailable();
115 $a->save_timestamp($stamp1, "network");
121 * @brief Returns the MySQL server version string
123 * This function discriminate between the deprecated mysql API and the current
124 * object-oriented mysqli API. Example of returned string: 5.5.46-0+deb8u1
128 public static function server_info() {
129 if (self::$_server_info == '') {
130 switch (self::$driver) {
132 self::$_server_info = self::$db->getAttribute(PDO::ATTR_SERVER_VERSION);
135 self::$_server_info = self::$db->server_info;
138 self::$_server_info = mysql_get_server_info(self::$db);
142 return self::$_server_info;
146 * @brief Returns the selected database name
150 public static function database_name() {
151 $ret = self::p("SELECT DATABASE() AS `db`");
152 $data = self::inArray($ret);
153 return $data[0]['db'];
157 * @brief Analyze a database query and log this if some conditions are met.
159 * @param string $query The database query that will be analyzed
161 private static function log_index($query) {
164 if (empty($a->config["system"]["db_log_index"])) {
168 // Don't explain an explain statement
169 if (strtolower(substr($query, 0, 7)) == "explain") {
173 // Only do the explain on "select", "update" and "delete"
174 if (!in_array(strtolower(substr($query, 0, 6)), array("select", "update", "delete"))) {
178 $r = self::p("EXPLAIN ".$query);
179 if (!dbm::is_result($r)) {
183 $watchlist = explode(',', $a->config["system"]["db_log_index_watch"]);
184 $blacklist = explode(',', $a->config["system"]["db_log_index_blacklist"]);
186 while ($row = dba::fetch($r)) {
187 if ((intval($a->config["system"]["db_loglimit_index"]) > 0)) {
188 $log = (in_array($row['key'], $watchlist) &&
189 ($row['rows'] >= intval($a->config["system"]["db_loglimit_index"])));
194 if ((intval($a->config["system"]["db_loglimit_index_high"]) > 0) && ($row['rows'] >= intval($a->config["system"]["db_loglimit_index_high"]))) {
198 if (in_array($row['key'], $blacklist) || ($row['key'] == "")) {
203 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
204 @file_put_contents($a->config["system"]["db_log_index"], datetime_convert()."\t".
205 $row['key']."\t".$row['rows']."\t".$row['Extra']."\t".
206 basename($backtrace[1]["file"])."\t".
207 $backtrace[1]["line"]."\t".$backtrace[2]["function"]."\t".
208 substr($query, 0, 2000)."\n", FILE_APPEND);
213 public static function escape($str) {
214 switch (self::$driver) {
216 return substr(@self::$db->quote($str, PDO::PARAM_STR), 1, -1);
218 return @self::$db->real_escape_string($str);
220 return @mysql_real_escape_string($str,self::$db);
224 public static function connected() {
225 switch (self::$driver) {
227 // Not sure if this really is working like expected
228 $connected = (self::$db->getAttribute(PDO::ATTR_CONNECTION_STATUS) != "");
231 $connected = self::$db->ping();
234 $connected = mysql_ping(self::$db);
241 * @brief Replaces ANY_VALUE() function by MIN() function,
242 * if the database server does not support ANY_VALUE().
244 * Considerations for Standard SQL, or MySQL with ONLY_FULL_GROUP_BY (default since 5.7.5).
245 * ANY_VALUE() is available from MySQL 5.7.5 https://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html
246 * A standard fall-back is to use MIN().
248 * @param string $sql An SQL string without the values
249 * @return string The input SQL string modified if necessary.
251 public static function any_value_fallback($sql) {
252 $server_info = self::server_info();
253 if (version_compare($server_info, '5.7.5', '<') ||
254 (stripos($server_info, 'MariaDB') !== false)) {
255 $sql = str_ireplace('ANY_VALUE(', 'MIN(', $sql);
261 * @brief beautifies the query - useful for "SHOW PROCESSLIST"
263 * This is safe when we bind the parameters later.
264 * The parameter values aren't part of the SQL.
266 * @param string $sql An SQL string without the values
267 * @return string The input SQL string modified if necessary.
269 public static function clean_query($sql) {
270 $search = array("\t", "\n", "\r", " ");
271 $replace = array(' ', ' ', ' ', ' ');
274 $sql = str_replace($search, $replace, $sql);
275 } while ($oldsql != $sql);
282 * @brief Replaces the ? placeholders with the parameters in the $args array
284 * @param string $sql SQL query
285 * @param array $args The parameters that are to replace the ? placeholders
286 * @return string The replaced SQL query
288 private static function replace_parameters($sql, $args) {
290 foreach ($args AS $param => $value) {
291 if (is_int($args[$param]) || is_float($args[$param])) {
292 $replace = intval($args[$param]);
294 $replace = "'".self::escape($args[$param])."'";
297 $pos = strpos($sql, '?', $offset);
298 if ($pos !== false) {
299 $sql = substr_replace($sql, $replace, $pos, 1);
301 $offset = $pos + strlen($replace);
307 * @brief Convert parameter array to an universal form
308 * @param array $args Parameter array
309 * @return array universalized parameter array
311 private static function getParam($args) {
314 // When the second function parameter is an array then use this as the parameter array
315 if ((count($args) > 0) && (is_array($args[1]))) {
323 * @brief Executes a prepared statement that returns data
324 * @usage Example: $r = p("SELECT * FROM `item` WHERE `guid` = ?", $guid);
326 * Please only use it with complicated queries.
327 * For all regular queries please use dba::select or dba::exists
329 * @param string $sql SQL statement
330 * @return object statement object
332 public static function p($sql) {
335 $stamp1 = microtime(true);
337 $params = self::getParam(func_get_args());
339 // Renumber the array keys to be sure that they fit
342 foreach ($params AS $param) {
343 // Avoid problems with some MySQL servers and boolean values. See issue #3645
344 if (is_bool($param)) {
345 $param = (int)$param;
347 $args[++$i] = $param;
350 if (!self::$connected) {
354 if ((substr_count($sql, '?') != count($args)) && (count($args) > 0)) {
355 // Question: Should we continue or stop the query here?
356 logger('Parameter mismatch. Query "'.$sql.'" - Parameters '.print_r($args, true), LOGGER_DEBUG);
359 $sql = self::clean_query($sql);
360 $sql = self::any_value_fallback($sql);
364 if (x($a->config,'system') && x($a->config['system'], 'db_callstack')) {
365 $sql = "/*".System::callstack()." */ ".$sql;
370 self::$affected_rows = 0;
372 // We have to make some things different if this function is called from "e"
373 $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2);
375 if (isset($trace[1])) {
376 $called_from = $trace[1];
378 // We use just something that is defined to avoid warnings
379 $called_from = $trace[0];
381 // We are having an own error logging in the function "e"
382 $called_from_e = ($called_from['function'] == 'e');
384 switch (self::$driver) {
386 // If there are no arguments we use "query"
387 if (count($args) == 0) {
388 if (!$retval = self::$db->query($sql)) {
389 $errorInfo = self::$db->errorInfo();
390 self::$error = $errorInfo[2];
391 self::$errorno = $errorInfo[1];
395 self::$affected_rows = $retval->rowCount();
399 if (!$stmt = self::$db->prepare($sql)) {
400 $errorInfo = self::$db->errorInfo();
401 self::$error = $errorInfo[2];
402 self::$errorno = $errorInfo[1];
407 foreach ($args AS $param => $value) {
408 $stmt->bindParam($param, $args[$param]);
411 if (!$stmt->execute()) {
412 $errorInfo = $stmt->errorInfo();
413 self::$error = $errorInfo[2];
414 self::$errorno = $errorInfo[1];
418 self::$affected_rows = $retval->rowCount();
422 // There are SQL statements that cannot be executed with a prepared statement
423 $parts = explode(' ', $orig_sql);
424 $command = strtolower($parts[0]);
425 $can_be_prepared = in_array($command, array('select', 'update', 'insert', 'delete'));
427 // The fallback routine is called as well when there are no arguments
428 if (!$can_be_prepared || (count($args) == 0)) {
429 $retval = self::$db->query(self::replace_parameters($sql, $args));
430 if (self::$db->errno) {
431 self::$error = self::$db->error;
432 self::$errorno = self::$db->errno;
435 if (isset($retval->num_rows)) {
436 self::$affected_rows = $retval->num_rows;
438 self::$affected_rows = self::$db->affected_rows;
444 $stmt = self::$db->stmt_init();
446 if (!$stmt->prepare($sql)) {
447 self::$error = $stmt->error;
448 self::$errorno = $stmt->errno;
455 foreach ($args AS $param => $value) {
456 if (is_int($args[$param])) {
458 } elseif (is_float($args[$param])) {
460 } elseif (is_string($args[$param])) {
465 $values[] = &$args[$param];
468 if (count($values) > 0) {
469 array_unshift($values, $params);
470 call_user_func_array(array($stmt, 'bind_param'), $values);
473 if (!$stmt->execute()) {
474 self::$error = self::$db->error;
475 self::$errorno = self::$db->errno;
478 $stmt->store_result();
480 self::$affected_rows = $retval->affected_rows;
484 // For the old "mysql" functions we cannot use prepared statements
485 $retval = mysql_query(self::replace_parameters($sql, $args), self::$db);
486 if (mysql_errno(self::$db)) {
487 self::$error = mysql_error(self::$db);
488 self::$errorno = mysql_errno(self::$db);
490 self::$affected_rows = mysql_affected_rows($retval);
492 // Due to missing mysql_* support this here wasn't tested at all
493 // See here: http://php.net/manual/en/function.mysql-num-rows.php
494 if (self::$affected_rows <= 0) {
495 self::$affected_rows = mysql_num_rows($retval);
501 // We are having an own error logging in the function "e"
502 if ((self::$errorno != 0) && !$called_from_e) {
503 // We have to preserve the error code, somewhere in the logging it get lost
504 $error = self::$error;
505 $errorno = self::$errorno;
507 logger('DB Error '.self::$errorno.': '.self::$error."\n".
508 System::callstack(8)."\n".self::replace_parameters($sql, $params));
510 self::$error = $error;
511 self::$errorno = $errorno;
514 $a->save_timestamp($stamp1, 'database');
516 if (x($a->config,'system') && x($a->config['system'], 'db_log')) {
518 $stamp2 = microtime(true);
519 $duration = (float)($stamp2 - $stamp1);
521 if (($duration > $a->config["system"]["db_loglimit"])) {
522 $duration = round($duration, 3);
523 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
525 @file_put_contents($a->config["system"]["db_log"], datetime_convert()."\t".$duration."\t".
526 basename($backtrace[1]["file"])."\t".
527 $backtrace[1]["line"]."\t".$backtrace[2]["function"]."\t".
528 substr(self::replace_parameters($sql, $args), 0, 2000)."\n", FILE_APPEND);
535 * @brief Executes a prepared statement like UPDATE or INSERT that doesn't return data
537 * Please use dba::delete, dba::insert, dba::update, ... instead
539 * @param string $sql SQL statement
540 * @return boolean Was the query successfull? False is returned only if an error occurred
542 public static function e($sql) {
545 $stamp = microtime(true);
547 $params = self::getParam(func_get_args());
549 // In a case of a deadlock we are repeating the query 20 times
553 $stmt = self::p($sql, $params);
555 if (is_bool($stmt)) {
557 } elseif (is_object($stmt)) {
565 } while ((self::$errorno == 1213) && (--$timeout > 0));
567 if (self::$errorno != 0) {
568 // We have to preserve the error code, somewhere in the logging it get lost
569 $error = self::$error;
570 $errorno = self::$errorno;
572 logger('DB Error '.self::$errorno.': '.self::$error."\n".
573 System::callstack(8)."\n".self::replace_parameters($sql, $params));
575 self::$error = $error;
576 self::$errorno = $errorno;
579 $a->save_timestamp($stamp, "database_write");
585 * @brief Check if data exists
587 * @param string $table Table name
588 * @param array $condition array of fields for condition
590 * @return boolean Are there rows for that condition?
592 public static function exists($table, $condition) {
599 $array_element = each($condition);
600 $array_key = $array_element['key'];
601 if (!is_int($array_key)) {
602 $fields = array($array_key);
605 $stmt = self::select($table, $fields, $condition, array('limit' => 1, 'only_query' => true));
607 if (is_bool($stmt)) {
610 $retval = (self::num_rows($stmt) > 0);
619 * @brief Fetches the first row
621 * Please use dba::select or dba::exists whenever this is possible.
623 * @param string $sql SQL statement
624 * @return array first row of query
626 public static function fetch_first($sql) {
627 $params = self::getParam(func_get_args());
629 $stmt = self::p($sql, $params);
631 if (is_bool($stmt)) {
634 $retval = self::fetch($stmt);
643 * @brief Returns the number of affected rows of the last statement
645 * @return int Number of rows
647 public static function affected_rows() {
648 return self::$affected_rows;
652 * @brief Returns the number of columns of a statement
654 * @param object Statement object
655 * @return int Number of columns
657 public static function columnCount($stmt) {
658 if (!is_object($stmt)) {
661 switch (self::$driver) {
663 return $stmt->columnCount();
665 return $stmt->field_count;
667 return mysql_affected_rows($stmt);
672 * @brief Returns the number of rows of a statement
674 * @param object Statement object
675 * @return int Number of rows
677 public static function num_rows($stmt) {
678 if (!is_object($stmt)) {
681 switch (self::$driver) {
683 return $stmt->rowCount();
685 return $stmt->num_rows;
687 return mysql_num_rows($stmt);
693 * @brief Fetch a single row
695 * @param object $stmt statement object
696 * @return array current row
698 public static function fetch($stmt) {
699 if (!is_object($stmt)) {
703 switch (self::$driver) {
705 return $stmt->fetch(PDO::FETCH_ASSOC);
707 if (get_class($stmt) == 'mysqli_result') {
708 return $stmt->fetch_assoc();
711 // This code works, but is slow
713 // Bind the result to a result array
717 for ($x = 0; $x < $stmt->field_count; $x++) {
718 $cols[] = &$cols_num[$x];
721 call_user_func_array(array($stmt, 'bind_result'), $cols);
723 if (!$stmt->fetch()) {
728 // We need to get the field names for the array keys
729 // It seems that there is no better way to do this.
730 $result = $stmt->result_metadata();
731 $fields = $result->fetch_fields();
734 foreach ($cols_num AS $param => $col) {
735 $columns[$fields[$param]->name] = $col;
739 return mysql_fetch_array($stmt, MYSQL_ASSOC);
744 * @brief Insert a row into a table
746 * @param string $table Table name
747 * @param array $param parameter array
748 * @param bool $on_duplicate_update Do an update on a duplicate entry
750 * @return boolean was the insert successfull?
752 public static function insert($table, $param, $on_duplicate_update = false) {
753 $sql = "INSERT INTO `".self::escape($table)."` (`".implode("`, `", array_keys($param))."`) VALUES (".
754 substr(str_repeat("?, ", count($param)), 0, -2).")";
756 if ($on_duplicate_update) {
757 $sql .= " ON DUPLICATE KEY UPDATE `".implode("` = ?, `", array_keys($param))."` = ?";
759 $values = array_values($param);
760 $param = array_merge_recursive($values, $values);
763 return self::e($sql, $param);
767 * @brief Fetch the id of the last insert command
769 * @return integer Last inserted id
771 public static function lastInsertId() {
772 switch (self::$driver) {
774 $id = self::$db->lastInsertId();
777 $id = self::$db->insert_id;
780 $id = mysql_insert_id(self::$db);
787 * @brief Locks a table for exclusive write access
789 * This function can be extended in the future to accept a table array as well.
791 * @param string $table Table name
793 * @return boolean was the lock successful?
795 public static function lock($table) {
796 // See here: https://dev.mysql.com/doc/refman/5.7/en/lock-tables-and-transactions.html
797 self::e("SET autocommit=0");
798 $success = self::e("LOCK TABLES `".self::escape($table)."` WRITE");
800 self::e("SET autocommit=1");
802 self::$in_transaction = true;
808 * @brief Unlocks all locked tables
810 * @return boolean was the unlock successful?
812 public static function unlock() {
813 // See here: https://dev.mysql.com/doc/refman/5.7/en/lock-tables-and-transactions.html
815 $success = self::e("UNLOCK TABLES");
816 self::e("SET autocommit=1");
817 self::$in_transaction = false;
822 * @brief Starts a transaction
824 * @return boolean Was the command executed successfully?
826 public static function transaction() {
827 if (!self::e('COMMIT')) {
830 if (!self::e('START TRANSACTION')) {
833 self::$in_transaction = true;
838 * @brief Does a commit
840 * @return boolean Was the command executed successfully?
842 public static function commit() {
843 if (!self::e('COMMIT')) {
846 self::$in_transaction = false;
851 * @brief Does a rollback
853 * @return boolean Was the command executed successfully?
855 public static function rollback() {
856 if (!self::e('ROLLBACK')) {
859 self::$in_transaction = false;
864 * @brief Build the array with the table relations
866 * The array is build from the database definitions in dbstructure.php
868 * This process must only be started once, since the value is cached.
870 private static function build_relation_data() {
871 $definition = db_definition();
873 foreach ($definition AS $table => $structure) {
874 foreach ($structure['fields'] AS $field => $field_struct) {
875 if (isset($field_struct['relation'])) {
876 foreach ($field_struct['relation'] AS $rel_table => $rel_field) {
877 self::$relation[$rel_table][$rel_field][$table][] = $field;
885 * @brief Delete a row from a table
887 * @param string $table Table name
888 * @param array $param parameter array
889 * @param boolean $in_process Internal use: Only do a commit after the last delete
890 * @param array $callstack Internal use: prevent endless loops
892 * @return boolean|array was the delete successfull? When $in_process is set: deletion data
894 public static function delete($table, $param, $in_process = false, &$callstack = array()) {
897 // Create a key for the loop prevention
898 $key = $table.':'.implode(':', array_keys($param)).':'.implode(':', $param);
900 // We quit when this key already exists in the callstack.
901 if (isset($callstack[$key])) {
905 $callstack[$key] = true;
907 $table = self::escape($table);
909 $commands[$key] = array('table' => $table, 'param' => $param);
911 // To speed up the whole process we cache the table relations
912 if (count(self::$relation) == 0) {
913 self::build_relation_data();
916 // Is there a relation entry for the table?
917 if (isset(self::$relation[$table])) {
918 // We only allow a simple "one field" relation.
919 $field = array_keys(self::$relation[$table])[0];
920 $rel_def = array_values(self::$relation[$table])[0];
922 // Create a key for preventing double queries
923 $qkey = $field.'-'.$table.':'.implode(':', array_keys($param)).':'.implode(':', $param);
925 // When the search field is the relation field, we don't need to fetch the rows
926 // This is useful when the leading record is already deleted in the frontend but the rest is done in the backend
927 if ((count($param) == 1) && ($field == array_keys($param)[0])) {
928 foreach ($rel_def AS $rel_table => $rel_fields) {
929 foreach ($rel_fields AS $rel_field) {
930 $retval = self::delete($rel_table, array($rel_field => array_values($param)[0]), true, $callstack);
931 $commands = array_merge($commands, $retval);
934 // We quit when this key already exists in the callstack.
935 } elseif (!isset($callstack[$qkey])) {
937 $callstack[$qkey] = true;
939 // Fetch all rows that are to be deleted
940 $data = self::select($table, array($field), $param);
942 while ($row = self::fetch($data)) {
943 // Now we accumulate the delete commands
944 $retval = self::delete($table, array($field => $row[$field]), true, $callstack);
945 $commands = array_merge($commands, $retval);
950 // Since we had split the delete command we don't need the original command anymore
951 unset($commands[$key]);
956 // Now we finalize the process
957 $do_transaction = !self::$in_transaction;
959 if ($do_transaction) {
963 $compacted = array();
966 foreach ($commands AS $command) {
967 $condition = $command['param'];
968 $array_element = each($condition);
969 $array_key = $array_element['key'];
970 if (is_int($array_key)) {
971 $condition_string = " WHERE ".array_shift($condition);
973 $condition_string = " WHERE `".implode("` = ? AND `", array_keys($condition))."` = ?";
976 if ((count($command['param']) > 1) || is_int($array_key)) {
977 $sql = "DELETE FROM `".$command['table']."`".$condition_string;
978 logger(self::replace_parameters($sql, $condition), LOGGER_DATA);
980 if (!self::e($sql, $condition)) {
981 if ($do_transaction) {
987 $key_table = $command['table'];
988 $key_param = array_keys($command['param'])[0];
989 $value = array_values($command['param'])[0];
991 // Split the SQL queries in chunks of 100 values
992 // We do the $i stuff here to make the code better readable
993 $i = $counter[$key_table][$key_param];
994 if (count($compacted[$key_table][$key_param][$i]) > 100) {
998 $compacted[$key_table][$key_param][$i][$value] = $value;
999 $counter[$key_table][$key_param] = $i;
1002 foreach ($compacted AS $table => $values) {
1003 foreach ($values AS $field => $field_value_list) {
1004 foreach ($field_value_list AS $field_values) {
1005 $sql = "DELETE FROM `".$table."` WHERE `".$field."` IN (".
1006 substr(str_repeat("?, ", count($field_values)), 0, -2).");";
1008 logger(self::replace_parameters($sql, $field_values), LOGGER_DATA);
1010 if (!self::e($sql, $field_values)) {
1011 if ($do_transaction) {
1019 if ($do_transaction) {
1029 * @brief Updates rows
1031 * Updates rows in the database. When $old_fields is set to an array,
1032 * the system will only do an update if the fields in that array changed.
1035 * Only the values in $old_fields are compared.
1036 * This is an intentional behaviour.
1039 * We include the timestamp field in $fields but not in $old_fields.
1040 * Then the row will only get the new timestamp when the other fields had changed.
1042 * When $old_fields is set to a boolean value the system will do this compare itself.
1043 * When $old_fields is set to "true" the system will do an insert if the row doesn't exists.
1046 * Only set $old_fields to a boolean value when you are sure that you will update a single row.
1047 * When you set $old_fields to "true" then $fields must contain all relevant fields!
1049 * @param string $table Table name
1050 * @param array $fields contains the fields that are updated
1051 * @param array $condition condition array with the key values
1052 * @param array|boolean $old_fields array with the old field values that are about to be replaced (true = update on duplicate)
1054 * @return boolean was the update successfull?
1056 public static function update($table, $fields, $condition, $old_fields = array()) {
1057 $table = self::escape($table);
1059 if (count($condition) > 0) {
1060 $array_element = each($condition);
1061 $array_key = $array_element['key'];
1062 if (is_int($array_key)) {
1063 $condition_string = " WHERE ".array_shift($condition);
1065 $condition_string = " WHERE `".implode("` = ? AND `", array_keys($condition))."` = ?";
1068 $condition_string = "";
1071 if (is_bool($old_fields)) {
1072 $do_insert = $old_fields;
1074 $old_fields = self::select($table, array(), $condition, array('limit' => 1));
1076 if (is_bool($old_fields)) {
1078 $values = array_merge($condition, $fields);
1079 return self::insert($table, $values, $do_insert);
1081 $old_fields = array();
1085 $do_update = (count($old_fields) == 0);
1087 foreach ($old_fields AS $fieldname => $content) {
1088 if (isset($fields[$fieldname])) {
1089 if ($fields[$fieldname] == $content) {
1090 unset($fields[$fieldname]);
1097 if (!$do_update || (count($fields) == 0)) {
1101 $sql = "UPDATE `".$table."` SET `".
1102 implode("` = ?, `", array_keys($fields))."` = ?".$condition_string;
1104 $params1 = array_values($fields);
1105 $params2 = array_values($condition);
1106 $params = array_merge_recursive($params1, $params2);
1108 return self::e($sql, $params);
1112 * @brief Select rows from a table
1114 * @param string $table Table name
1115 * @param array $fields array of selected fields
1116 * @param array $condition array of fields for condition
1117 * @param array $params array of several parameters
1119 * @return boolean|object If "limit" is equal "1" only a single row is returned, else a query object is returned
1123 * $fields = array("id", "uri", "uid", "network");
1125 * $condition = array("uid" => 1, "network" => 'dspr');
1127 * $condition = array("`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr');
1129 * $params = array("order" => array("id", "received" => true), "limit" => 1);
1131 * $data = dba::select($table, $fields, $condition, $params);
1133 public static function select($table, $fields = array(), $condition = array(), $params = array()) {
1138 if (count($fields) > 0) {
1139 $select_fields = "`".implode("`, `", array_values($fields))."`";
1141 $select_fields = "*";
1144 if (count($condition) > 0) {
1145 $array_element = each($condition);
1146 $array_key = $array_element['key'];
1147 if (is_int($array_key)) {
1148 $condition_string = " WHERE ".array_shift($condition);
1150 $condition_string = " WHERE `".implode("` = ? AND `", array_keys($condition))."` = ?";
1153 $condition_string = "";
1157 $single_row = false;
1159 if (isset($params['order'])) {
1160 $param_string .= " ORDER BY ";
1161 foreach ($params['order'] AS $fields => $order) {
1162 if (!is_int($fields)) {
1163 $param_string .= "`".$fields."` ".($order ? "DESC" : "ASC").", ";
1165 $param_string .= "`".$order."`, ";
1168 $param_string = substr($param_string, 0, -2);
1171 if (isset($params['limit']) && is_int($params['limit'])) {
1172 $param_string .= " LIMIT ".$params['limit'];
1173 $single_row = ($params['limit'] == 1);
1176 if (isset($params['only_query']) && $params['only_query']) {
1177 $single_row = !$params['only_query'];
1180 $sql = "SELECT ".$select_fields." FROM `".$table."`".$condition_string.$param_string;
1182 $result = self::p($sql, $condition);
1184 if (is_bool($result) || !$single_row) {
1187 $row = self::fetch($result);
1188 self::close($result);
1195 * @brief Fills an array with data from a query
1197 * @param object $stmt statement object
1198 * @return array Data array
1200 public static function inArray($stmt, $do_close = true) {
1201 if (is_bool($stmt)) {
1206 while ($row = self::fetch($stmt)) {
1216 * @brief Returns the error number of the last query
1218 * @return string Error number (0 if no error)
1220 public static function errorNo() {
1221 return self::$errorno;
1225 * @brief Returns the error message of the last query
1227 * @return string Error message ('' if no error)
1229 public static function errorMessage() {
1230 return self::$error;
1234 * @brief Closes the current statement
1236 * @param object $stmt statement object
1237 * @return boolean was the close successfull?
1239 public static function close($stmt) {
1240 if (!is_object($stmt)) {
1244 switch (self::$driver) {
1246 return $stmt->closeCursor();
1248 return $stmt->free_result();
1249 return $stmt->close();
1251 return mysql_free_result($stmt);
1256 function dbesc($str) {
1257 if (dba::$connected) {
1258 return(dba::escape($str));
1260 return(str_replace("'","\\'",$str));
1265 * @brief execute SQL query with printf style args - deprecated
1267 * Please use the dba:: functions instead:
1268 * dba::select, dba::exists, dba::insert
1269 * dba::delete, dba::update, dba::p, dba::e
1271 * @param $args Query parameters (1 to N parameters of different types)
1272 * @return array Query array
1275 $args = func_get_args();
1278 if (!dba::$connected) {
1282 $sql = dba::clean_query($sql);
1283 $sql = dba::any_value_fallback($sql);
1285 $stmt = @vsprintf($sql, $args);
1287 $ret = dba::p($stmt);
1289 if (is_bool($ret)) {
1293 $columns = dba::columnCount($ret);
1295 $data = dba::inArray($ret);
1297 if ((count($data) == 0) && ($columns == 0)) {
1304 function dba_timer() {
1305 return microtime(true);