Skip to content

Commit

Permalink
MDL-27148 use static counter instead of incrementing parameter name
Browse files Browse the repository at this point in the history
  • Loading branch information
skodak committed Apr 14, 2011
1 parent 91787c3 commit 906c957
Showing 1 changed file with 18 additions and 9 deletions.
27 changes: 18 additions & 9 deletions lib/dml/moodle_database.php
Original file line number Diff line number Diff line change
Expand Up @@ -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');
Expand Down Expand Up @@ -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).')';
Expand Down

0 comments on commit 906c957

Please sign in to comment.