Index: includes/database.inc =================================================================== RCS file: /cvs/drupal/drupal/includes/database.inc,v retrieving revision 1.42 diff -u -p -r1.42 database.inc --- includes/database.inc 27 Jul 2005 01:58:43 -0000 1.42 +++ includes/database.inc 8 Aug 2005 08:37:18 -0000 @@ -140,8 +140,13 @@ function db_set_active($name = 'default' * A string containing an SQL query. * @param ... * A variable number of arguments which are substituted into the query using - * printf() syntax. Instead of a variable number of query arguments, you may - * also pass a single array containing the query arguments. + * printf() syntax. The query arguments can be enclosed in one array instead. + * For INSERT and UPDATE queries the arguments should be present in an + * array in which the keys name the database columns. For UPDATE queries + * additional parameters can be passed as single arguments after the array. + * Examples: + * db_query('INSERT INTO {node} %a', array('nid' => 42, 'title' => 'foo bar', ...)); + * db_query('UPDATE {node} SET %a WHERE nid = %d', array('uid' => 42, 'title' => 'foo bar'), $node->nid); * @return * A database query result resource, or FALSE if the query was not executed * correctly. @@ -150,8 +155,19 @@ function db_query($query) { $args = func_get_args(); $query = db_prefix_tables($query); if (count($args) > 1) { + if (strpos($query, '%a') !== FALSE) { + $keys = array_keys($args[1]); + $placeholders = call_user_func_array('array_merge', array_map('_db_argument_type', $keys, $args[1])); + if (strpos($query, 'INSERT') !== FALSE) { + $replace = '('. implode(', ', $keys) .') VALUES ('. implode(', ', array_values($placeholders)) .')'; + } + else if (strpos($query, 'UPDATE') !== FALSE) { + $replace = implode(', ', array_keys($placeholders)); + } + $query = str_replace('%a', $replace, $query); + } if (is_array($args[1])) { - $args = array_merge(array($query), $args[1]); + $args = array_merge(array($query), $args[1], array_slice($args, 2)); } $args = array_map('db_escape_string', $args); $args[0] = $query; @@ -280,6 +296,26 @@ function db_rewrite_sql($query, $primary } /** + * Helper function for db_query + * @param $key + * Database column + * @param $value + * Query argument + * @return + * Array containing $key and sprintf modifier as key and sprintf modifier + * as value. + */ +function _db_argument_type($key, &$value) { + if (is_numeric($value) || is_bool($value)) { + $value = (int) $value; + return array("$key = %d" => '%d'); + } + else { + return array("$key = '%s'" => "'%s'"); + } +} + +/** * @} End of "defgroup database". */