Is there a way to retrieve the query that was used to generate a PDO Prepared statement object?
Is there a way to retrieve the query that was used to generate a PDO Prepared statement object?
The simplest way to achieve what you want is:
$statement->debugDumpParams();
Just make sure you add it after executing the statement.
This procedure works. Since debugDumpParams() doesn't return the output. Here is a little trick i designed.
// get the output before debugDumpParams() get executed
$before = ob_get_contents();
//start a new buffer
ob_start();
// dump params now
$smt->debugDumpParams();
// save the output in a new variable $data
$data = ob_get_contents();
// clean the output screen
ob_end_clean();
// display what was before debugDumpParams() got executed
printf("%s", $before);
$statement = "";
// Now for prepared statements
if (stristr($data, 'Sent SQL') !== false)
{
// begin extracting from "Sent SQL"
$begin = stristr($data, 'Sent SQL');
// get the first ] square bracket
$square = strpos($begin, "]");
// collect sql
$begin = substr($begin, $square + 1);
$ending = strpos($begin, "Params");
$sql = substr($begin, 0, $ending);
$sql = trim($sql);
// sql statement here
$statement = $sql;
}
else
{
if (stristr($data, 'SQL') !== false)
{
$begin = stristr($data, 'SQL');
// get the first ] square bracket
$square = strpos($begin, "]");
// collect sql
$begin = substr($begin, $square + 1);
$ending = strpos($begin, "Params");
$sql = substr($begin, 0, $ending);
$sql = trim($sql);
$statement = $sql;
}
}
// statement here
echo $statement;
Hope this helps.