从 PDO 准备好的语句中获取原始 SQL 查询字符串
在准备好的语句上调用 PDOStatement::execute() 时,有没有办法让原始 SQL 字符串执行?出于调试目的,这将非常有用。
Is there a way to get the raw SQL string executed when calling PDOStatement::execute() on a prepared statement? For debugging purposes this would be extremely useful.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(16)
我修改了该方法以包括处理 WHERE IN (?) 等语句的数组输出。
更新:刚刚添加了对 NULL 值和重复 $params 的检查,因此实际的 $param 值不会被修改。
干得好,bigwebguy,谢谢!
I modified the method to include handling output of arrays for statements like WHERE IN (?).
UPDATE: Just added check for NULL value and duplicated $params so actual $param values are not modified.
Great work bigwebguy and thanks!
解决方案是主动在查询中添加错误并打印错误消息:
标准输出:
请务必注意,它仅打印前 80 个字符的查询。
A solution is to voluntarily put an error in the query and to print the error's message:
Standard output:
It is important to note that it only prints the first 80 characters of the query.
可能有点晚了,但现在有了
PDOStatement::debugDumpParams
您可以在 官方 php 文档 上找到更多信息
示例:
A bit late probably but now there is
PDOStatement::debugDumpParams
You can find more on the official php docs
Example:
Mike 在代码中添加了更多内容 - 遍历值以添加单引号
Added a little bit more to the code by Mike - walk the values to add single quotes
PDOStatement 有一个公共属性 $queryString。它应该是你想要的。
我刚刚注意到 PDOStatement 有一个未记录的方法 debugDumpParams() 您可能还想看看。
PDOStatement has a public property $queryString. It should be what you want.
I've just notice that PDOStatement has an undocumented method debugDumpParams() which you may also want to look at.
为了满足我自己的需要,我花了很多时间研究这种情况。这个和其他几个 SO 线程对我帮助很大,所以我想分享我的想法。
虽然在故障排除时访问插入的查询字符串是一个显着的好处,但我们希望能够仅维护某些查询的日志(因此,为此目的使用数据库日志并不理想)。我们还希望能够使用日志在任何给定时间重新创建表的条件,因此,我们需要确保插入的字符串已正确转义。最后,我们希望将此功能扩展到我们的整个代码库,而必须尽可能少地重写它(截止日期、营销等;你知道它是怎么回事)。
我的解决方案是扩展默认 PDOStatement 对象的功能以缓存参数化值(或引用),并且在执行语句时,使用 PDO 对象的功能在将参数注入回查询时正确转义参数细绳。然后,我们可以结合语句对象的执行方法并记录当时执行的实际查询(或至少尽可能忠实地再现)。
正如我所说,我们不想修改整个代码库来添加此功能,因此我们覆盖了 PDOStatement 的默认
bindParam()
和bindValue()
方法对象,缓存绑定数据,然后调用parent::bindParam() 或parent::bindValue()。这使得我们现有的代码库能够继续正常运行。最后,当调用
execute()
方法时,我们执行插值并将结果字符串提供为新属性E_PDOStatement->fullQuery
。这可以输出以查看查询,或者例如写入日志文件。该扩展以及安装和配置说明可在 github 上找到:
https://github.com/noahheck/E_PDOStatement< /a>
免责声明:
显然,正如我所提到的,我编写了这个扩展。因为它是在许多线程的帮助下开发的,所以我想在这里发布我的解决方案,以防其他人遇到这些线程,就像我一样。
I spent a good deal of time researching this situation for my own needs. This and several other SO threads helped me a great deal, so I wanted to share what I came up with.
While having access to the interpolated query string is a significant benefit while troubleshooting, we wanted to be able to maintain a log of only certain queries (therefore, using the database logs for this purpose was not ideal). We also wanted to be able to use the logs to recreate the condition of the tables at any given time, therefore, we needed to make certain the interpolated strings were escaped properly. Finally, we wanted to extend this functionality to our entire code base having to re-write as little of it as possible (deadlines, marketing, and such; you know how it is).
My solution was to extend the functionality of the default PDOStatement object to cache the parameterized values (or references), and when the statement is executed, use the functionality of the PDO object to properly escape the parameters when they are injected back in to the query string. We could then tie in to execute method of the statement object and log the actual query that was executed at that time (or at least as faithful of a reproduction as possible).
As I said, we didn't want to modify the entire code base to add this functionality, so we overwrite the default
bindParam()
andbindValue()
methods of the PDOStatement object, do our caching of the bound data, then callparent::bindParam()
or parent::bindValue()
. This allowed our existing code base to continue to function as normal.Finally, when the
execute()
method is called, we perform our interpolation and provide the resultant string as a new propertyE_PDOStatement->fullQuery
. This can be output to view the query or, for example, written to a log file.The extension, along with installation and configuration instructions, are available on github:
https://github.com/noahheck/E_PDOStatement
DISCLAIMER:
Obviously, as I mentioned, I wrote this extension. Because it was developed with help from many threads here, I wanted to post my solution here in case anyone else comes across these threads, just as I did.
您可以扩展 PDOStatement 类来捕获有界变量并存储它们以供以后使用。然后可以添加 2 种方法,一种用于变量清理 ( debugBindedVariables ),另一种用于打印包含这些变量的查询 ( debugQuery ):
然后您可以使用这个继承的类进行调试。
导致
You can extend PDOStatement class to capture the bounded variables and store them for later use. Then 2 methods may be added, one for variable sanitizing ( debugBindedVariables ) and another to print the query with those variables ( debugQuery ):
And then you can use this inherited class for debugging purpouses.
Resulting in
现有的答案似乎都不完整或安全,因此我想出了这个函数,它具有以下改进:
适用于未命名 (
?
) 和命名 (:foo< /code>) 参数。
使用 PDO::quote() 正确转义值不是
NULL
、int
、float
或bool
。正确处理包含
"?"
和":foo"
的字符串值,不会将它们误认为占位符。我确信它可以进一步改进。
就我而言,我最终只是记录了实际的“未准备的查询”(即包含占位符的 SQL)以及 JSON 编码的参数。但是,此代码可能会用于某些您确实需要插入最终 SQL 查询的用例。
None of the existing answers seemed complete or safe, so I came up with this function, which has the following improvements:
works with both unnamed (
?
) and named (:foo
) parameters.using PDO::quote() to properly escape values which are not
NULL
,int
,float
orbool
.properly handles string values containing
"?"
and":foo"
without mistaking them for placeholders.I'm sure it can be improved further.
In my case, I eventually ended up just logging the actual "unprepared query" (i.e. SQL containing placeholders) along with JSON-encoded parameters. However, this code might come in use for some use cases where you really need to interpolate the final SQL query.
您可以使用
sprintf(str_replace('?', '"%s"', $sql), ...$params);
这是一个示例:
注意这仅适用于 PHP >= 5.6
You can use
sprintf(str_replace('?', '"%s"', $sql), ...$params);
Here is an example:
Note this only works for PHP >= 5.6
提到的 $queryString 属性可能只会返回传入的查询,而不将参数替换为其值。在 .Net 中,我的查询执行器的 catch 部分对参数进行了简单的搜索替换,并将其替换为所提供的值,以便错误日志可以显示用于查询的实际值。您应该能够枚举 PHP 中的参数,并将参数替换为其分配的值。
The $queryString property mentioned will probably only return the query passed in, without the parameters replaced with their values. In .Net, I have the catch part of my query executer do a simple search replace on the parameters with their values which was supplied so that the error log can show actual values that were being used for the query. You should be able to enumerate the parameters in PHP, and replace the parameters with their assigned value.
我知道这个问题有点老了,但是,我很久以前就在使用这段代码(我已经使用了 @chris-go 的响应),现在,这些代码在 PHP 7.2 中已经过时了,
我将发布更新的代码这些代码的版本(主要代码来自 @bigwebguy,@mike 和 @chris-go,所有答案这个问题):
请注意代码的更改是在 array_walk() 函数上,用匿名函数替换 create_function 。这使得这些优秀的代码具有功能并且与 PHP 7.2 兼容(并且希望未来的版本也是如此)。
I know this question is a bit old, but, I'm using this code since lot time ago (I've used response from @chris-go), and now, these code are obsolete with PHP 7.2
I'll post an updated version of these code (Credit for the main code are from @bigwebguy, @mike and @chris-go, all of them answers of this question):
Note the change on the code are on array_walk() function, replacing create_function by an anonymous function. This make these good piece of code functional and compatible with PHP 7.2 (and hope future versions too).
preg_replace 对我不起作用,当 binding_ 超过 9 时,binging_1 和 binding_10 被 str_replace 替换(留下 0),所以我向后进行了替换:
}
希望有人觉得它有用。
preg_replace didn't work for me and when binding_ was over 9, binding_1 and binding_10 was replaced with str_replace (leaving the 0 behind), so I made the replacements backwards:
}
Hope someone finds it useful.
我需要在绑定参数后记录完整的查询字符串,所以这是我的代码中的一部分。希望这对遇到同样问题的每个人都有用。
I need to log full query string after bind param so this is a piece in my code. Hope, it is useful for everyone hat has the same issue.
Mike的答案在您使用“重用”绑定值之前效果很好。
例如:
Mike的答案只能替换第一个:search,但不能替换第二个。
因此,我重写了他的答案,以使用可以正确重复使用的多个参数。
Mike's answer is working good until you are using the "re-use" bind value.
For example:
The Mike's answer can only replace first :search but not the second.
So, I rewrite his answer to work with multiple parameters that can re-used properly.
我假设您的意思是您想要最终的 SQL 查询,并将参数值插入其中。我知道这对于调试很有用,但这不是准备好的语句的工作方式。参数不会与客户端的准备好的语句组合,因此 PDO 永远不应该访问与其参数组合的查询字符串。
当你执行prepare()时,SQL语句被发送到数据库服务器,而当你执行execute()时,参数被单独发送。 MySQL 的常规查询日志确实显示了最终的 SQL,其中包含执行()后插入的值。以下是我的一般查询日志的摘录。我从 mysql CLI 运行查询,而不是从 PDO 运行查询,但原理是相同的。
如果您设置 PDO 属性 PDO::ATTR_EMULATE_PREPARES,您也可以获得您想要的结果。在此模式下,PDO 将参数插入到 SQL 查询中,并在您执行()时发送整个查询。 这不是真正的准备好的查询。您将通过在execute() 之前将变量插入到SQL 字符串中来规避准备好的查询的好处。
回复 @afilina 的评论:
不,文本 SQL 查询在执行期间不与参数结合。所以 PDO 没有什么可以向您展示的。
在内部,如果您使用 PDO::ATTR_EMULATE_PREPARES,PDO 会在准备和执行之前创建 SQL 查询的副本并在其中插入参数值。但 PDO 不会公开此修改后的 SQL 查询。
PDOStatement 对象有一个属性 $queryString,但这仅在 PDOStatement 的构造函数中设置,并且在使用参数重写查询时不会更新。
对于 PDO 来说,要求他们公开重写的查询是一个合理的功能请求。但即使这样也不会给你“完整”的查询,除非你使用 PDO::ATTR_EMULATE_PREPARES。
这就是为什么我展示了上面使用 MySQL 服务器的通用查询日志的解决方法,因为在这种情况下,即使是带有参数占位符的准备好的查询也会在服务器上重写,并将参数值回填到查询字符串中。但这仅在日志记录期间完成,而不是在查询执行期间完成。
I assume you mean that you want the final SQL query, with parameter values interpolated into it. I understand that this would be useful for debugging, but it is not the way prepared statements work. Parameters are not combined with a prepared statement on the client-side, so PDO should never have access to the query string combined with its parameters.
The SQL statement is sent to the database server when you do prepare(), and the parameters are sent separately when you do execute(). MySQL's general query log does show the final SQL with values interpolated after you execute(). Below is an excerpt from my general query log. I ran the queries from the mysql CLI, not from PDO, but the principle is the same.
You can also get what you want if you set the PDO attribute PDO::ATTR_EMULATE_PREPARES. In this mode, PDO interpolate parameters into the SQL query and sends the whole query when you execute(). This is not a true prepared query. You will circumvent the benefits of prepared queries by interpolating variables into the SQL string before execute().
Re comment from @afilina:
No, the textual SQL query is not combined with the parameters during execution. So there's nothing for PDO to show you.
Internally, if you use PDO::ATTR_EMULATE_PREPARES, PDO makes a copy of the SQL query and interpolates parameter values into it before doing the prepare and execute. But PDO does not expose this modified SQL query.
The PDOStatement object has a property $queryString, but this is set only in the constructor for the PDOStatement, and it's not updated when the query is rewritten with parameters.
It would be a reasonable feature request for PDO to ask them to expose the rewritten query. But even that wouldn't give you the "complete" query unless you use PDO::ATTR_EMULATE_PREPARES.
This is why I show the workaround above of using the MySQL server's general query log, because in this case even a prepared query with parameter placeholders is rewritten on the server, with parameter values backfilled into the query string. But this is only done during logging, not during query execution.