2 use \Friendica\Core\System;
3 use Friendica\Database\DBM;
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 // No suitable SQL driver was found.
97 if (!self::$connected) {
100 system_unavailable();
103 $a->save_timestamp($stamp1, "network");
109 * @brief Returns the MySQL server version string
111 * This function discriminate between the deprecated mysql API and the current
112 * object-oriented mysqli API. Example of returned string: 5.5.46-0+deb8u1
116 public static function server_info() {
117 if (self::$_server_info == '') {
118 switch (self::$driver) {
120 self::$_server_info = self::$db->getAttribute(PDO::ATTR_SERVER_VERSION);
123 self::$_server_info = self::$db->server_info;
127 return self::$_server_info;
131 * @brief Returns the selected database name
135 public static function database_name() {
136 $ret = self::p("SELECT DATABASE() AS `db`");
137 $data = self::inArray($ret);
138 return $data[0]['db'];
142 * @brief Analyze a database query and log this if some conditions are met.
144 * @param string $query The database query that will be analyzed
146 private static function log_index($query) {
149 if (empty($a->config["system"]["db_log_index"])) {
153 // Don't explain an explain statement
154 if (strtolower(substr($query, 0, 7)) == "explain") {
158 // Only do the explain on "select", "update" and "delete"
159 if (!in_array(strtolower(substr($query, 0, 6)), array("select", "update", "delete"))) {
163 $r = self::p("EXPLAIN ".$query);
164 if (!DBM::is_result($r)) {
168 $watchlist = explode(',', $a->config["system"]["db_log_index_watch"]);
169 $blacklist = explode(',', $a->config["system"]["db_log_index_blacklist"]);
171 while ($row = dba::fetch($r)) {
172 if ((intval($a->config["system"]["db_loglimit_index"]) > 0)) {
173 $log = (in_array($row['key'], $watchlist) &&
174 ($row['rows'] >= intval($a->config["system"]["db_loglimit_index"])));
179 if ((intval($a->config["system"]["db_loglimit_index_high"]) > 0) && ($row['rows'] >= intval($a->config["system"]["db_loglimit_index_high"]))) {
183 if (in_array($row['key'], $blacklist) || ($row['key'] == "")) {
188 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
189 @file_put_contents($a->config["system"]["db_log_index"], datetime_convert()."\t".
190 $row['key']."\t".$row['rows']."\t".$row['Extra']."\t".
191 basename($backtrace[1]["file"])."\t".
192 $backtrace[1]["line"]."\t".$backtrace[2]["function"]."\t".
193 substr($query, 0, 2000)."\n", FILE_APPEND);
198 public static function escape($str) {
199 switch (self::$driver) {
201 return substr(@self::$db->quote($str, PDO::PARAM_STR), 1, -1);
203 return @self::$db->real_escape_string($str);
207 public static function connected() {
210 switch (self::$driver) {
212 $r = dba::p("SELECT 1");
213 if (DBM::is_result($r)) {
214 $row = dba::inArray($r);
215 $connected = ($row[0]['1'] == '1');
219 $connected = self::$db->ping();
226 * @brief Replaces ANY_VALUE() function by MIN() function,
227 * if the database server does not support ANY_VALUE().
229 * Considerations for Standard SQL, or MySQL with ONLY_FULL_GROUP_BY (default since 5.7.5).
230 * ANY_VALUE() is available from MySQL 5.7.5 https://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html
231 * A standard fall-back is to use MIN().
233 * @param string $sql An SQL string without the values
234 * @return string The input SQL string modified if necessary.
236 public static function any_value_fallback($sql) {
237 $server_info = self::server_info();
238 if (version_compare($server_info, '5.7.5', '<') ||
239 (stripos($server_info, 'MariaDB') !== false)) {
240 $sql = str_ireplace('ANY_VALUE(', 'MIN(', $sql);
246 * @brief beautifies the query - useful for "SHOW PROCESSLIST"
248 * This is safe when we bind the parameters later.
249 * The parameter values aren't part of the SQL.
251 * @param string $sql An SQL string without the values
252 * @return string The input SQL string modified if necessary.
254 public static function clean_query($sql) {
255 $search = array("\t", "\n", "\r", " ");
256 $replace = array(' ', ' ', ' ', ' ');
259 $sql = str_replace($search, $replace, $sql);
260 } while ($oldsql != $sql);
267 * @brief Replaces the ? placeholders with the parameters in the $args array
269 * @param string $sql SQL query
270 * @param array $args The parameters that are to replace the ? placeholders
271 * @return string The replaced SQL query
273 private static function replace_parameters($sql, $args) {
275 foreach ($args AS $param => $value) {
276 if (is_int($args[$param]) || is_float($args[$param])) {
277 $replace = intval($args[$param]);
279 $replace = "'".self::escape($args[$param])."'";
282 $pos = strpos($sql, '?', $offset);
283 if ($pos !== false) {
284 $sql = substr_replace($sql, $replace, $pos, 1);
286 $offset = $pos + strlen($replace);
292 * @brief Convert parameter array to an universal form
293 * @param array $args Parameter array
294 * @return array universalized parameter array
296 private static function getParam($args) {
299 // When the second function parameter is an array then use this as the parameter array
300 if ((count($args) > 0) && (is_array($args[1]))) {
308 * @brief Executes a prepared statement that returns data
309 * @usage Example: $r = p("SELECT * FROM `item` WHERE `guid` = ?", $guid);
311 * Please only use it with complicated queries.
312 * For all regular queries please use dba::select or dba::exists
314 * @param string $sql SQL statement
315 * @return object statement object
317 public static function p($sql) {
320 $stamp1 = microtime(true);
322 $params = self::getParam(func_get_args());
324 // Renumber the array keys to be sure that they fit
327 foreach ($params AS $param) {
328 // Avoid problems with some MySQL servers and boolean values. See issue #3645
329 if (is_bool($param)) {
330 $param = (int)$param;
332 $args[++$i] = $param;
335 if (!self::$connected) {
339 if ((substr_count($sql, '?') != count($args)) && (count($args) > 0)) {
340 // Question: Should we continue or stop the query here?
341 logger('Parameter mismatch. Query "'.$sql.'" - Parameters '.print_r($args, true), LOGGER_DEBUG);
344 $sql = self::clean_query($sql);
345 $sql = self::any_value_fallback($sql);
349 if (x($a->config,'system') && x($a->config['system'], 'db_callstack')) {
350 $sql = "/*".System::callstack()." */ ".$sql;
355 self::$affected_rows = 0;
357 // We have to make some things different if this function is called from "e"
358 $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2);
360 if (isset($trace[1])) {
361 $called_from = $trace[1];
363 // We use just something that is defined to avoid warnings
364 $called_from = $trace[0];
366 // We are having an own error logging in the function "e"
367 $called_from_e = ($called_from['function'] == 'e');
369 switch (self::$driver) {
371 // If there are no arguments we use "query"
372 if (count($args) == 0) {
373 if (!$retval = self::$db->query($sql)) {
374 $errorInfo = self::$db->errorInfo();
375 self::$error = $errorInfo[2];
376 self::$errorno = $errorInfo[1];
380 self::$affected_rows = $retval->rowCount();
384 if (!$stmt = self::$db->prepare($sql)) {
385 $errorInfo = self::$db->errorInfo();
386 self::$error = $errorInfo[2];
387 self::$errorno = $errorInfo[1];
392 foreach ($args AS $param => $value) {
393 $stmt->bindParam($param, $args[$param]);
396 if (!$stmt->execute()) {
397 $errorInfo = $stmt->errorInfo();
398 self::$error = $errorInfo[2];
399 self::$errorno = $errorInfo[1];
403 self::$affected_rows = $retval->rowCount();
407 // There are SQL statements that cannot be executed with a prepared statement
408 $parts = explode(' ', $orig_sql);
409 $command = strtolower($parts[0]);
410 $can_be_prepared = in_array($command, array('select', 'update', 'insert', 'delete'));
412 // The fallback routine is called as well when there are no arguments
413 if (!$can_be_prepared || (count($args) == 0)) {
414 $retval = self::$db->query(self::replace_parameters($sql, $args));
415 if (self::$db->errno) {
416 self::$error = self::$db->error;
417 self::$errorno = self::$db->errno;
420 if (isset($retval->num_rows)) {
421 self::$affected_rows = $retval->num_rows;
423 self::$affected_rows = self::$db->affected_rows;
429 $stmt = self::$db->stmt_init();
431 if (!$stmt->prepare($sql)) {
432 self::$error = $stmt->error;
433 self::$errorno = $stmt->errno;
440 foreach ($args AS $param => $value) {
441 if (is_int($args[$param])) {
443 } elseif (is_float($args[$param])) {
445 } elseif (is_string($args[$param])) {
450 $values[] = &$args[$param];
453 if (count($values) > 0) {
454 array_unshift($values, $params);
455 call_user_func_array(array($stmt, 'bind_param'), $values);
458 if (!$stmt->execute()) {
459 self::$error = self::$db->error;
460 self::$errorno = self::$db->errno;
463 $stmt->store_result();
465 self::$affected_rows = $retval->affected_rows;
470 // We are having an own error logging in the function "e"
471 if ((self::$errorno != 0) && !$called_from_e) {
472 // We have to preserve the error code, somewhere in the logging it get lost
473 $error = self::$error;
474 $errorno = self::$errorno;
476 logger('DB Error '.self::$errorno.': '.self::$error."\n".
477 System::callstack(8)."\n".self::replace_parameters($sql, $params));
479 self::$error = $error;
480 self::$errorno = $errorno;
483 $a->save_timestamp($stamp1, 'database');
485 if (x($a->config,'system') && x($a->config['system'], 'db_log')) {
487 $stamp2 = microtime(true);
488 $duration = (float)($stamp2 - $stamp1);
490 if (($duration > $a->config["system"]["db_loglimit"])) {
491 $duration = round($duration, 3);
492 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
494 @file_put_contents($a->config["system"]["db_log"], datetime_convert()."\t".$duration."\t".
495 basename($backtrace[1]["file"])."\t".
496 $backtrace[1]["line"]."\t".$backtrace[2]["function"]."\t".
497 substr(self::replace_parameters($sql, $args), 0, 2000)."\n", FILE_APPEND);
504 * @brief Executes a prepared statement like UPDATE or INSERT that doesn't return data
506 * Please use dba::delete, dba::insert, dba::update, ... instead
508 * @param string $sql SQL statement
509 * @return boolean Was the query successfull? False is returned only if an error occurred
511 public static function e($sql) {
514 $stamp = microtime(true);
516 $params = self::getParam(func_get_args());
518 // In a case of a deadlock we are repeating the query 20 times
522 $stmt = self::p($sql, $params);
524 if (is_bool($stmt)) {
526 } elseif (is_object($stmt)) {
534 } while ((self::$errorno == 1213) && (--$timeout > 0));
536 if (self::$errorno != 0) {
537 // We have to preserve the error code, somewhere in the logging it get lost
538 $error = self::$error;
539 $errorno = self::$errorno;
541 logger('DB Error '.self::$errorno.': '.self::$error."\n".
542 System::callstack(8)."\n".self::replace_parameters($sql, $params));
544 self::$error = $error;
545 self::$errorno = $errorno;
548 $a->save_timestamp($stamp, "database_write");
554 * @brief Check if data exists
556 * @param string $table Table name
557 * @param array $condition array of fields for condition
559 * @return boolean Are there rows for that condition?
561 public static function exists($table, $condition) {
568 $array_element = each($condition);
569 $array_key = $array_element['key'];
570 if (!is_int($array_key)) {
571 $fields = array($array_key);
574 $stmt = self::select($table, $fields, $condition, array('limit' => 1, 'only_query' => true));
576 if (is_bool($stmt)) {
579 $retval = (self::num_rows($stmt) > 0);
588 * @brief Fetches the first row
590 * Please use dba::select or dba::exists whenever this is possible.
592 * @param string $sql SQL statement
593 * @return array first row of query
595 public static function fetch_first($sql) {
596 $params = self::getParam(func_get_args());
598 $stmt = self::p($sql, $params);
600 if (is_bool($stmt)) {
603 $retval = self::fetch($stmt);
612 * @brief Returns the number of affected rows of the last statement
614 * @return int Number of rows
616 public static function affected_rows() {
617 return self::$affected_rows;
621 * @brief Returns the number of columns of a statement
623 * @param object Statement object
624 * @return int Number of columns
626 public static function columnCount($stmt) {
627 if (!is_object($stmt)) {
630 switch (self::$driver) {
632 return $stmt->columnCount();
634 return $stmt->field_count;
639 * @brief Returns the number of rows of a statement
641 * @param object Statement object
642 * @return int Number of rows
644 public static function num_rows($stmt) {
645 if (!is_object($stmt)) {
648 switch (self::$driver) {
650 return $stmt->rowCount();
652 return $stmt->num_rows;
658 * @brief Fetch a single row
660 * @param object $stmt statement object
661 * @return array current row
663 public static function fetch($stmt) {
664 if (!is_object($stmt)) {
668 switch (self::$driver) {
670 return $stmt->fetch(PDO::FETCH_ASSOC);
672 if (get_class($stmt) == 'mysqli_result') {
673 return $stmt->fetch_assoc();
676 // This code works, but is slow
678 // Bind the result to a result array
682 for ($x = 0; $x < $stmt->field_count; $x++) {
683 $cols[] = &$cols_num[$x];
686 call_user_func_array(array($stmt, 'bind_result'), $cols);
688 if (!$stmt->fetch()) {
693 // We need to get the field names for the array keys
694 // It seems that there is no better way to do this.
695 $result = $stmt->result_metadata();
696 $fields = $result->fetch_fields();
699 foreach ($cols_num AS $param => $col) {
700 $columns[$fields[$param]->name] = $col;
707 * @brief Insert a row into a table
709 * @param string $table Table name
710 * @param array $param parameter array
711 * @param bool $on_duplicate_update Do an update on a duplicate entry
713 * @return boolean was the insert successfull?
715 public static function insert($table, $param, $on_duplicate_update = false) {
716 $sql = "INSERT INTO `".self::escape($table)."` (`".implode("`, `", array_keys($param))."`) VALUES (".
717 substr(str_repeat("?, ", count($param)), 0, -2).")";
719 if ($on_duplicate_update) {
720 $sql .= " ON DUPLICATE KEY UPDATE `".implode("` = ?, `", array_keys($param))."` = ?";
722 $values = array_values($param);
723 $param = array_merge_recursive($values, $values);
726 return self::e($sql, $param);
730 * @brief Fetch the id of the last insert command
732 * @return integer Last inserted id
734 public static function lastInsertId() {
735 switch (self::$driver) {
737 $id = self::$db->lastInsertId();
740 $id = self::$db->insert_id;
747 * @brief Locks a table for exclusive write access
749 * This function can be extended in the future to accept a table array as well.
751 * @param string $table Table name
753 * @return boolean was the lock successful?
755 public static function lock($table) {
756 // See here: https://dev.mysql.com/doc/refman/5.7/en/lock-tables-and-transactions.html
757 self::e("SET autocommit=0");
758 $success = self::e("LOCK TABLES `".self::escape($table)."` WRITE");
760 self::e("SET autocommit=1");
762 self::$in_transaction = true;
768 * @brief Unlocks all locked tables
770 * @return boolean was the unlock successful?
772 public static function unlock() {
773 // See here: https://dev.mysql.com/doc/refman/5.7/en/lock-tables-and-transactions.html
775 $success = self::e("UNLOCK TABLES");
776 self::e("SET autocommit=1");
777 self::$in_transaction = false;
782 * @brief Starts a transaction
784 * @return boolean Was the command executed successfully?
786 public static function transaction() {
787 if (!self::e('COMMIT')) {
790 if (!self::e('START TRANSACTION')) {
793 self::$in_transaction = true;
798 * @brief Does a commit
800 * @return boolean Was the command executed successfully?
802 public static function commit() {
803 if (!self::e('COMMIT')) {
806 self::$in_transaction = false;
811 * @brief Does a rollback
813 * @return boolean Was the command executed successfully?
815 public static function rollback() {
816 if (!self::e('ROLLBACK')) {
819 self::$in_transaction = false;
824 * @brief Build the array with the table relations
826 * The array is build from the database definitions in dbstructure.php
828 * This process must only be started once, since the value is cached.
830 private static function build_relation_data() {
831 $definition = db_definition();
833 foreach ($definition AS $table => $structure) {
834 foreach ($structure['fields'] AS $field => $field_struct) {
835 if (isset($field_struct['relation'])) {
836 foreach ($field_struct['relation'] AS $rel_table => $rel_field) {
837 self::$relation[$rel_table][$rel_field][$table][] = $field;
845 * @brief Delete a row from a table
847 * @param string $table Table name
848 * @param array $param parameter array
849 * @param boolean $in_process Internal use: Only do a commit after the last delete
850 * @param array $callstack Internal use: prevent endless loops
852 * @return boolean|array was the delete successfull? When $in_process is set: deletion data
854 public static function delete($table, $param, $in_process = false, &$callstack = array()) {
857 // Create a key for the loop prevention
858 $key = $table.':'.implode(':', array_keys($param)).':'.implode(':', $param);
860 // We quit when this key already exists in the callstack.
861 if (isset($callstack[$key])) {
865 $callstack[$key] = true;
867 $table = self::escape($table);
869 $commands[$key] = array('table' => $table, 'param' => $param);
871 // To speed up the whole process we cache the table relations
872 if (count(self::$relation) == 0) {
873 self::build_relation_data();
876 // Is there a relation entry for the table?
877 if (isset(self::$relation[$table])) {
878 // We only allow a simple "one field" relation.
879 $field = array_keys(self::$relation[$table])[0];
880 $rel_def = array_values(self::$relation[$table])[0];
882 // Create a key for preventing double queries
883 $qkey = $field.'-'.$table.':'.implode(':', array_keys($param)).':'.implode(':', $param);
885 // When the search field is the relation field, we don't need to fetch the rows
886 // This is useful when the leading record is already deleted in the frontend but the rest is done in the backend
887 if ((count($param) == 1) && ($field == array_keys($param)[0])) {
888 foreach ($rel_def AS $rel_table => $rel_fields) {
889 foreach ($rel_fields AS $rel_field) {
890 $retval = self::delete($rel_table, array($rel_field => array_values($param)[0]), true, $callstack);
891 $commands = array_merge($commands, $retval);
894 // We quit when this key already exists in the callstack.
895 } elseif (!isset($callstack[$qkey])) {
897 $callstack[$qkey] = true;
899 // Fetch all rows that are to be deleted
900 $data = self::select($table, array($field), $param);
902 while ($row = self::fetch($data)) {
903 // Now we accumulate the delete commands
904 $retval = self::delete($table, array($field => $row[$field]), true, $callstack);
905 $commands = array_merge($commands, $retval);
910 // Since we had split the delete command we don't need the original command anymore
911 unset($commands[$key]);
916 // Now we finalize the process
917 $do_transaction = !self::$in_transaction;
919 if ($do_transaction) {
923 $compacted = array();
926 foreach ($commands AS $command) {
927 $condition = $command['param'];
928 $array_element = each($condition);
929 $array_key = $array_element['key'];
930 if (is_int($array_key)) {
931 $condition_string = " WHERE ".array_shift($condition);
933 $condition_string = " WHERE `".implode("` = ? AND `", array_keys($condition))."` = ?";
936 if ((count($command['param']) > 1) || is_int($array_key)) {
937 $sql = "DELETE FROM `".$command['table']."`".$condition_string;
938 logger(self::replace_parameters($sql, $condition), LOGGER_DATA);
940 if (!self::e($sql, $condition)) {
941 if ($do_transaction) {
947 $key_table = $command['table'];
948 $key_param = array_keys($command['param'])[0];
949 $value = array_values($command['param'])[0];
951 // Split the SQL queries in chunks of 100 values
952 // We do the $i stuff here to make the code better readable
953 $i = $counter[$key_table][$key_param];
954 if (count($compacted[$key_table][$key_param][$i]) > 100) {
958 $compacted[$key_table][$key_param][$i][$value] = $value;
959 $counter[$key_table][$key_param] = $i;
962 foreach ($compacted AS $table => $values) {
963 foreach ($values AS $field => $field_value_list) {
964 foreach ($field_value_list AS $field_values) {
965 $sql = "DELETE FROM `".$table."` WHERE `".$field."` IN (".
966 substr(str_repeat("?, ", count($field_values)), 0, -2).");";
968 logger(self::replace_parameters($sql, $field_values), LOGGER_DATA);
970 if (!self::e($sql, $field_values)) {
971 if ($do_transaction) {
979 if ($do_transaction) {
989 * @brief Updates rows
991 * Updates rows in the database. When $old_fields is set to an array,
992 * the system will only do an update if the fields in that array changed.
995 * Only the values in $old_fields are compared.
996 * This is an intentional behaviour.
999 * We include the timestamp field in $fields but not in $old_fields.
1000 * Then the row will only get the new timestamp when the other fields had changed.
1002 * When $old_fields is set to a boolean value the system will do this compare itself.
1003 * When $old_fields is set to "true" the system will do an insert if the row doesn't exists.
1006 * Only set $old_fields to a boolean value when you are sure that you will update a single row.
1007 * When you set $old_fields to "true" then $fields must contain all relevant fields!
1009 * @param string $table Table name
1010 * @param array $fields contains the fields that are updated
1011 * @param array $condition condition array with the key values
1012 * @param array|boolean $old_fields array with the old field values that are about to be replaced (true = update on duplicate)
1014 * @return boolean was the update successfull?
1016 public static function update($table, $fields, $condition, $old_fields = array()) {
1017 $table = self::escape($table);
1019 if (count($condition) > 0) {
1020 $array_element = each($condition);
1021 $array_key = $array_element['key'];
1022 if (is_int($array_key)) {
1023 $condition_string = " WHERE ".array_shift($condition);
1025 $condition_string = " WHERE `".implode("` = ? AND `", array_keys($condition))."` = ?";
1028 $condition_string = "";
1031 if (is_bool($old_fields)) {
1032 $do_insert = $old_fields;
1034 $old_fields = self::select($table, array(), $condition, array('limit' => 1));
1036 if (is_bool($old_fields)) {
1038 $values = array_merge($condition, $fields);
1039 return self::insert($table, $values, $do_insert);
1041 $old_fields = array();
1045 $do_update = (count($old_fields) == 0);
1047 foreach ($old_fields AS $fieldname => $content) {
1048 if (isset($fields[$fieldname])) {
1049 if ($fields[$fieldname] == $content) {
1050 unset($fields[$fieldname]);
1057 if (!$do_update || (count($fields) == 0)) {
1061 $sql = "UPDATE `".$table."` SET `".
1062 implode("` = ?, `", array_keys($fields))."` = ?".$condition_string;
1064 $params1 = array_values($fields);
1065 $params2 = array_values($condition);
1066 $params = array_merge_recursive($params1, $params2);
1068 return self::e($sql, $params);
1072 * @brief Select rows from a table
1074 * @param string $table Table name
1075 * @param array $fields array of selected fields
1076 * @param array $condition array of fields for condition
1077 * @param array $params array of several parameters
1079 * @return boolean|object If "limit" is equal "1" only a single row is returned, else a query object is returned
1083 * $fields = array("id", "uri", "uid", "network");
1085 * $condition = array("uid" => 1, "network" => 'dspr');
1087 * $condition = array("`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr');
1089 * $params = array("order" => array("id", "received" => true), "limit" => 1);
1091 * $data = dba::select($table, $fields, $condition, $params);
1093 public static function select($table, $fields = array(), $condition = array(), $params = array()) {
1098 if (count($fields) > 0) {
1099 $select_fields = "`".implode("`, `", array_values($fields))."`";
1101 $select_fields = "*";
1104 if (count($condition) > 0) {
1105 $array_element = each($condition);
1106 $array_key = $array_element['key'];
1107 if (is_int($array_key)) {
1108 $condition_string = " WHERE ".array_shift($condition);
1110 $condition_string = " WHERE `".implode("` = ? AND `", array_keys($condition))."` = ?";
1113 $condition_string = "";
1117 $single_row = false;
1119 if (isset($params['order'])) {
1120 $param_string .= " ORDER BY ";
1121 foreach ($params['order'] AS $fields => $order) {
1122 if (!is_int($fields)) {
1123 $param_string .= "`".$fields."` ".($order ? "DESC" : "ASC").", ";
1125 $param_string .= "`".$order."`, ";
1128 $param_string = substr($param_string, 0, -2);
1131 if (isset($params['limit']) && is_int($params['limit'])) {
1132 $param_string .= " LIMIT ".$params['limit'];
1133 $single_row = ($params['limit'] == 1);
1136 if (isset($params['only_query']) && $params['only_query']) {
1137 $single_row = !$params['only_query'];
1140 $sql = "SELECT ".$select_fields." FROM `".$table."`".$condition_string.$param_string;
1142 $result = self::p($sql, $condition);
1144 if (is_bool($result) || !$single_row) {
1147 $row = self::fetch($result);
1148 self::close($result);
1155 * @brief Fills an array with data from a query
1157 * @param object $stmt statement object
1158 * @return array Data array
1160 public static function inArray($stmt, $do_close = true) {
1161 if (is_bool($stmt)) {
1166 while ($row = self::fetch($stmt)) {
1176 * @brief Returns the error number of the last query
1178 * @return string Error number (0 if no error)
1180 public static function errorNo() {
1181 return self::$errorno;
1185 * @brief Returns the error message of the last query
1187 * @return string Error message ('' if no error)
1189 public static function errorMessage() {
1190 return self::$error;
1194 * @brief Closes the current statement
1196 * @param object $stmt statement object
1197 * @return boolean was the close successfull?
1199 public static function close($stmt) {
1200 if (!is_object($stmt)) {
1204 switch (self::$driver) {
1206 return $stmt->closeCursor();
1208 $stmt->free_result();
1209 return $stmt->close();
1214 function dbesc($str) {
1215 if (dba::$connected) {
1216 return(dba::escape($str));
1218 return(str_replace("'","\\'",$str));
1223 * @brief execute SQL query with printf style args - deprecated
1225 * Please use the dba:: functions instead:
1226 * dba::select, dba::exists, dba::insert
1227 * dba::delete, dba::update, dba::p, dba::e
1229 * @param $args Query parameters (1 to N parameters of different types)
1230 * @return array Query array
1233 $args = func_get_args();
1236 if (!dba::$connected) {
1240 $sql = dba::clean_query($sql);
1241 $sql = dba::any_value_fallback($sql);
1243 $stmt = @vsprintf($sql, $args);
1245 $ret = dba::p($stmt);
1247 if (is_bool($ret)) {
1251 $columns = dba::columnCount($ret);
1253 $data = dba::inArray($ret);
1255 if ((count($data) == 0) && ($columns == 0)) {
1262 function dba_timer() {
1263 return microtime(true);