I am working on a simple SQL debugger which will accept parameterized variables and try to replace them accordingly so that if a piece of SQL has an issue then I can copy+paste it directly into my RDBMS to work with the query and hopefully debug an issue quicker.
So far I essentially have this, but it is replacing too much:
<?php
$sql = "select *
from table_name
where comment like :a and
email = :b and
status = :c";
$patterns = array();
$patterns[0] = '/:a/';
$patterns[1] = '/:b/';
$patterns[2] = '/:c/';
$replacements = array();
$replacements[0] = "'%that is a nice :b but this one%'";
$replacements[1] = "'monkeyzeus@example.com'";
$replacements[2] = "'active'";
echo preg_replace($patterns, $replacements, $sql);
Resulting in
select *
from table_name
where comment like '%that is a nice 'monkeyzeus@example.com' but this one%' and
email = 'monkeyzeus@example.com' and
status = 'active'
Notice that 'monkeyzeus@example.com'
from position 1 is making it into the :b
from position 0.
I've found this question, Can preg_replace make multiple search and replace operations in one shot?, but I cannot make heads or tails of it because I am certainly no regex expert.
Update. Just wanted to share the final product:
function debug_sql($sql = NULL, $params = NULL)
{
return (
$sql !== NULL && is_array($params) && $params ? // $sql and $params is required
strtr( // Feed this function the sql and the params which need to be replaced
$sql,
array_map( // Replace single-quotes within the param items with two single-quotes and surround param in single-quotes
function($p)
{
return "'".str_replace("'", "''", $p)."'"; // Basic Oracle escaping
},
$params
)
) :
$sql
);
}