Last active
March 16, 2018 06:03
-
-
Save picasso250/40d831cd586ca2b1b0cbeb1f10e5a323 to your computer and use it in GitHub Desktop.
merge sql placeholder ? and :x
This file contains hidden or 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
<?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; | |
} |
This file contains hidden or 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
<?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