From 906c957b631118a1ad28925850b2f19c45ce93c7 Mon Sep 17 00:00:00 2001 From: Petr Skoda Date: Thu, 14 Apr 2011 14:50:35 +0200 Subject: [PATCH] MDL-27148 use static counter instead of incrementing parameter name --- lib/dml/moodle_database.php | 27 ++++++++++++++++++--------- 1 file changed, 18 insertions(+), 9 deletions(-) diff --git a/lib/dml/moodle_database.php b/lib/dml/moodle_database.php index b647ca9adb771..b1e65d8552013 100644 --- a/lib/dml/moodle_database.php +++ b/lib/dml/moodle_database.php @@ -567,13 +567,15 @@ protected function where_clause_list($field, array $values) { * Constructs IN() or = sql fragment * @param mixed $items single or array of values * @param int $type bound param type SQL_PARAMS_QM or SQL_PARAMS_NAMED - * @param string named param placeholder start - * @param bool true means equal, false not equal + * @param string $prefix named parameter placeholder prefix (unique counter value is appended to each parameter name) + * @param bool $equal true means equal, false not equal * @param mixed $onemptyitems defines the behavior when the array of items is empty. Defaults to false, * meaning throw exceptions. Other values will become part of the returned SQL fragment. * @return array - $sql and $params */ - public function get_in_or_equal($items, $type=SQL_PARAMS_QM, $start='param0000', $equal=true, $onemptyitems=false) { + public function get_in_or_equal($items, $type=SQL_PARAMS_QM, $prefix='param', $equal=true, $onemptyitems=false) { + static $counter = 1; // guarantees unique parameters in each request + // default behavior, throw exception on empty array if (is_array($items) and empty($items) and $onemptyitems === false) { throw new coding_exception('moodle_database::get_in_or_equal() does not accept empty arrays'); @@ -603,19 +605,26 @@ public function get_in_or_equal($items, $type=SQL_PARAMS_QM, $start='param0000', } } else if ($type == SQL_PARAMS_NAMED) { + if (empty($prefix)) { + $prefix = 'param'; + } + if (!is_array($items)){ - $sql = $equal ? "= :$start" : "<> :$start"; - $params = array($start=>$items); + $param = $prefix.$counter++; + $sql = $equal ? "= :$param" : "<> :$param"; + $params = array($param=>$items); } else if (count($items) == 1) { - $sql = $equal ? "= :$start" : "<> :$start"; + $param = $prefix.$counter++; + $sql = $equal ? "= :$param" : "<> :$param"; $item = reset($items); - $params = array($start=>$item); + $params = array($param=>$item); } else { $params = array(); $sql = array(); foreach ($items as $item) { - $params[$start] = $item; - $sql[] = ':'.$start++; + $param = $prefix.$counter++; + $params[$param] = $item; + $sql[] = ':'.$param; } if ($equal) { $sql = 'IN ('.implode(',', $sql).')';