Get query back from PDO prepared statement

PhpMysqlPdo

Php Problem Overview


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

Php Solutions


Solution 1 - Php

Solution 2 - Php

The simplest way to achieve what you want is:

$statement->debugDumpParams();

Just make sure you add it after executing the statement.

Solution 3 - Php

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.

Solution 4 - Php

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionChrisRView Question on Stackoverflow
Solution 1 - PhpArkhView Answer on Stackoverflow
Solution 2 - PhpHaddock-sanView Answer on Stackoverflow
Solution 3 - PhpNoah HeckView Answer on Stackoverflow
Solution 4 - PhpIfeanyi AmadiView Answer on Stackoverflow