I stumbled upon this question from two years ago.
Is there a way to get the raw SQL string executed when calling PDOStatement::execute() on a prepare
The following static method takes a PDO query template (an SQL query with ?
and/or :name
placeholders) and interpolates the parameters:
static public function getDebugFullQuery($query, $params = array()){
if(is_array($params) && count($params)){
$search = [];
$replace = [];
foreach($params as $k => $p){
$pos = strpos($query, ":{$k}");
if($pos !== false){
$query = substr($query, 0, $pos) . "%!-!{$k}!-!%" . substr($query, $pos + strlen($k) + 1);
}
else {
$pos = strpos($query, "?");
if($pos !== false){
$query = substr($query, 0, $pos) . "%!-!{$k}!-!%" . substr($query, $pos + 1);
}
else {
break;
}
}
$search[] = "%!-!{$k}!-!%";
$replace[] = "'" . str_replace(array("\r", "\n", "'"), array("\\\\r", "\\\\n", "\\'"), $p) . "'";
}
if(count($search)){
$query = str_replace($search, $replace, $query);
}
}
return $query;
}
As indicated by the method name, you should use this for debugging purposes only.