Skip to content

Instantly share code, notes, and snippets.

@spcheema
Last active February 18, 2019 23:31
Show Gist options
  • Save spcheema/7b396bba7938f113a7aeb276b3383b22 to your computer and use it in GitHub Desktop.
Save spcheema/7b396bba7938f113a7aeb276b3383b22 to your computer and use it in GitHub Desktop.
Get a raw query from prepared pdo statement help for debugging.
/**
* Replaces any parameter placeholders in a query with the value of that
* parameter. Useful for debugging. Assumes anonymous parameters from
* $params are are in the same order as specified in $query
*
* @param string $query The sql query with parameter placeholders
* @param array $params The array of substitution parameters
* @return string The interpolated query
*
* @link https://stackoverflow.com/questions/210564/getting-raw-sql-query-string-from-pdo-prepared-statements
* @see Chris go answer
* A big thanks to @bigwebguy, @Mike, @Etienne Martin and @Chris Go
*/
public static function interpolateQuery($query, $params) {
$keys = array();
$values = $params;
# build a regular expression for each parameter
foreach ($params as $key => $value) {
if (is_string($key)) {
$keys[] = '/:'.$key.'/';
} else {
$keys[] = '/[?]/';
}
if (is_array($value))
$values[$key] = implode(',', $value);
if (is_null($value))
$values[$key] = 'NULL';
}
// Walk the array to see if we can add single-quotes to strings
array_walk($values, create_function('&$v, $k', 'if (!is_numeric($v) && $v!="NULL") $v = "\'".$v."\'";'));
$query = preg_replace($keys, $values, $query, 1, $count);
return $query;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment