php 从 PDO 准备好的语句中获取查询
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2243177/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get query back from PDO prepared statement
提问by ChrisR
Is there a way to retrieve the query that was used to generate a PDO Prepared statement object?
有没有办法检索用于生成 PDO 准备语句对象的查询?
采纳答案by Arkh
回答by myesain
If you aren't opposed to extending the default \PDO and \PDOStatement object, you might consider looking at:
如果您不反对扩展默认的 \PDO 和 \PDOStatement 对象,您可以考虑查看:
github.com/noahheck/E_PDOStatement
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.
这个 PDO 扩展允许您查看完整的查询语句作为可能在数据库级别执行的示例。它使用正则表达式来插入 PDO 语句的绑定参数。
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.
通过扩展默认的\PDOStatement 定义,E_PDOStatement 能够为默认功能提供这种增强,而无需修改您的正常工作流程。
Disclaimer: I created this extension.
免责声明:我创建了这个扩展。
I just hope it's helpful to someone else.
我只是希望它对其他人有帮助。
回答by Haddock-san
The simplest way to achieve what you want is:
实现您想要的最简单方法是:
$statement->debugDumpParams();
Just make sure you add it after executing the statement.
只要确保在执行语句后添加它。
回答by Ifeanyi Amadi
This procedure works. Since debugDumpParams() doesn't return the output. Here is a little trick i designed.
此过程有效。由于 debugDumpParams() 不返回输出。这是我设计的一个小技巧。
// 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.
希望这可以帮助。

