Skip to content

Instantly share code, notes, and snippets.

@dzentota
Forked from morozov/format-stmt.php
Created March 25, 2019 10:52
Show Gist options
  • Save dzentota/ea556fdea7c567e8ba2a1317d7aca316 to your computer and use it in GitHub Desktop.
Save dzentota/ea556fdea7c567e8ba2a1317d7aca316 to your computer and use it in GitHub Desktop.
Prepared Statements Debugging Snippets
<?php
function format_sugar_query(SugarQuery $query)
{
return format_builder(
$query->compile()
);
}
function format_builder(\Doctrine\DBAL\Query\QueryBuilder $builder)
{
return format_stmt(
$builder->getSQL(),
$builder->getParameters()
);
}
function format_stmt($sql, array $params)
{
$chunks = array();
$currentQuote = false;
for ($start = $i = 0, $length = strlen($sql); $i < $length; $i++) {
if (!$currentQuote && ($sql[$i] == "'" || $sql[$i] == '"')) {
$currentQuote = $sql[$i];
} elseif ($currentQuote && $sql[$i] == $currentQuote && $sql[$i - 1] != '\\') {
$currentQuote = false;
} elseif (!$currentQuote && $sql[$i] == '?') {
$chunks[] = substr($sql, $start, $i - $start);
$start = ++$i;
}
}
if ($currentQuote) {
return 'The statement contains non-terminated string literal';
}
$count = count($chunks);
if (count($params) != $count) {
return sprintf(
'The statement expects %d parameters, %d given',
$count,
count($params)
);
}
$chunks[] = substr($sql, $start);
foreach (array_values($params) as $i => $param) {
if (is_string($param)) {
$sql = sprintf("'%s'", addslashes($param));
} elseif (is_bool($param)) {
$sql = (int) $param;
} elseif ($param === null) {
$sql = 'NULL';
} else {
$sql = $param;
}
array_splice($chunks, $i * 2 + 1, 0, $sql);
}
return implode('', $chunks);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment