Skip to content

Instantly share code, notes, and snippets.

@hopeseekr
Last active August 29, 2015 14:05
Show Gist options
  • Save hopeseekr/1aa299e332b4819acb23 to your computer and use it in GitHub Desktop.
Save hopeseekr/1aa299e332b4819acb23 to your computer and use it in GitHub Desktop.
Output the raw SQL of a PDO prepared statement
<?php
/**
Usage:
$sql = "SELECT * FROM foo WHERE id=? AND name=? AND groupId=?";
$stmt = $pdo->prepare($sql);
$rawSQL = interpolateQuery($sql, array($id, $name, $groupId);
$stmt->execute(array($id, $name, $groupId));
**/
function interpolateQuery($query, $params) {
$keys = array();
# build a regular expression for each parameter
foreach ($params as $key => $value) {
if (is_string($key)) {
$keys[] = '/:'.$key.'/';
} else {
$keys[] = '/[?]/';
}
}
// Add quotes around strings.
foreach ($params as &$param) {
if (is_string($param)) {
$param = "'$param'";
}
}
$query = preg_replace($keys, $params, $query, 1, $count);
#trigger_error('replaced '.$count.' keys');
return $query;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment