Home » Php » php – Get query back from PDO prepared statement

php – Get query back from PDO prepared statement

Posted by: admin April 23, 2020 Leave a comment

Questions:

Is there a way to retrieve the query that was used to generate a PDO Prepared statement object?

How to&Answers:

Try $statement->queryString.

Answer:

If you aren’t opposed to extending the default \PDO and \PDOStatement object, you might consider looking at:

github.com/noahheck/E_PDOStatement

This extension to PDO allows you to see a full query statement as an example of what might be executed at the database level. It uses regex to interpolate the bound parameters of your PDO statement.

By extending the default \PDOStatement definition, E_PDOStatement is able to offer this enhancement to the default functionality without requiring modification to your normal work flow.

Disclaimer: I created this extension.

I just hope it’s helpful to someone else.

Answer:

The simplest way to achieve what you want is:

$statement->debugDumpParams();

Just make sure you add it after executing the statement.

Answer:

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.