Last active
July 23, 2019 22:29
-
-
Save andstor/dae3033886e96ecfa8ca8e62638bd84c to your computer and use it in GitHub Desktop.
PHP function for allowing use of a named SQL parameter multiple times. See https://docs.moodle.org/dev/Data_manipulation_API#Placeholders
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Make all named SQL parameters unique and | |
* generate a new parameter array with the unique parameters. | |
* @param string $sql The SQL with patameters to uniquify | |
* @param array $params The patameters to uniquify | |
* @return array | |
*/ | |
function uniquify_sql_params($sql, $params): array { | |
$pattern = "/:([a-zA-Z0-9_]+)/"; | |
$paramsres = []; | |
$processed = []; | |
$sqlres = preg_replace_callback($pattern, | |
function ($matches) use (&$params, &$paramsres, &$processed){ | |
$index = 1; | |
$key = substr($matches[0], 1); | |
if (!array_key_exists($key, $params)) { | |
return $matches[0]; | |
} | |
if (array_key_exists($key, $processed)) { | |
$processed[$key] += 1; | |
$index = $processed[$key]; | |
} else { | |
$processed[$key] = 1; | |
} | |
$newkey = $key . $index; | |
$paramsres[$newkey] = $params[$key]; | |
return $matches[0] . $index; | |
}, $sql); | |
foreach ($params as $param => $value) { | |
if (!array_key_exists($param, $paramsres) && !array_key_exists($param, $processed)) { | |
$paramsres[$param] = $value; | |
} | |
} | |
return [$sqlres, $paramsres]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment