Skip to content

Instantly share code, notes, and snippets.

@picasso250
Last active March 16, 2018 06:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save picasso250/40d831cd586ca2b1b0cbeb1f10e5a323 to your computer and use it in GitHub Desktop.
Save picasso250/40d831cd586ca2b1b0cbeb1f10e5a323 to your computer and use it in GitHub Desktop.
merge sql placeholder ? and :x
<?php
function quote_parse ($sql)
{
$n = mb_strlen($sql);
$state = 0;
$word = '';
$ret = [];
$quote = '';
for ($i=0; $i < $n; $i++) {
$ch = mb_substr($sql, $i, 1);
switch ($state) {
case 0:
if ($ch === '"' || $ch === "'") {
$quote = $ch;
if ($word !== '') {
$ret[]=$word;
$word = '';
}
$state = 1;
} else {
$word .= $ch;
}
break;
case 1:
if ($ch === $quote) {
$quote = $ch;
$ret[]="$quote$word$quote";
$word = '';
$quote = '';
$state = 0;
} else {
$word .= $ch;
}
break;
default:
# code...
break;
}
}
if ($word !== '') {
$ret[] = $word;
}
return $ret;
}
function sql_placeholder_merge($sql, $bind = [])
{
$list = quote_parse($sql);
$ret_sql = '';
foreach ($list as $key => $value) {
if ($value && ($value[0] === '"' || $value[0] === "'")) {
$ret_sql .= $value;
} else {
$ret_sql .= preg_replace_callback('/(\?|\:[a-zA-Z][a-zA-Z0-9_]*)/', function ($m) use(&$bind) {
$val = $m[1];
if ($val == '?') {
$val = quote (array_shift ($bind));
} else if ($val[0] == ':') {
if (isset($bind[$val])) {
$val = $bind[$val];
} else {
$val = $bind[substr($val, 1)];
}
$val = quote($val);
}
return $val;
}, $value);
}
}
return $ret_sql;
}
<?php
function sqlQuoteInto2 ($sql, $bind = null)
{
if (isset ($bind)) {
$sqlSplit = [];
$sql = preg_replace_callback('/(\?|\:[a-zA-Z][a-zA-Z0-9_]*)/', function ($m) use(&$bind, &$sqlSplit) {
$val = $m[1];
if ($val == '?') {
$val = quote (array_shift ($bind));
} else if ($val[0] == ':') {
if (isset($bind[$val])) {
$val = $bind[$val];
} else {
$val = $bind[substr($val, 1)];
}
$val = quote($val);
}
return $val;
}, $sql);
}
return $sql;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment