沃梦达 / 编程问答 / php问题 / 正文

PDO 调试 - 绑定后查看查询?

PDO Debugging - View Query AFTER Bind?(PDO 调试 - 绑定后查看查询?)

本文介绍了PDO 调试 - 绑定后查看查询?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能的重复:
从 PDO 准备好的语句中检索(或模拟)完整查询

我不明白为什么我的查询返回 0 行..它实现了一些非常动态的搜索功能,以及很多 if/loop 语句等.因此要调试它,我想看看到底是什么字符串正在发送到服务器.有没有办法通过 PHP 做到这一点?

I can't figure out why my query is returning 0 rows.. it implements some very dynamic search functionality, and a lot of if/loop statements etc. Therefor to debug it, I'd like to see EXACTLY what string is being sent to the server. Is there a way to do this through PHP?

有没有办法询问服务器上次查询是什么",或者告诉 PDO告诉我你发送了什么"?

Is there maybe a way to ask the server "what was the last query", or tell PDO "show me what you sent"?

我看到一个使用 str_replace 手动输入值代替 :fieldValue 的响应,但这可能是语法问题(或者它可能正在经历不正确的循环,等),此方法无济于事.

I saw one response using str_replace to manually enter the values in place of :fieldValue, but it's likely a syntax problem (or maybe it's going through an incorrect loop, etc), which this method doesn't help with.

使用 bindValue(":fieldValue", $value); 如果这有所不同.

Using bindValue(":fieldValue", $value); if that makes a difference.

编辑

结果是一个简单的 if ($var="true") { ... 应该是 if ($var=="true") { ....从这个意义上说,我猜 PHP 与 Java 不一样?无论哪种方式,问题仍然存在(因为我经常遇到这种情况).我不得不使用一系列 echo "You are Here"; 来找到这个错误,因为它在技术上有效但不正确.如果我有最后的 SQL 语句,我可以看到哦,我的代码添加了 where column = true,一定是通过了错误的 IF...".

Turns out it was a simple if ($var="true") { ... which should have been if ($var=="true") { .... PHP I guess is not the same as Java in that sense? Either way, the question still stands (as I run into this often). I had to use a series of echo "You are Here"; to find this error, as it was technically valid but not correct. If I had the final SQL statement, I could have seen "Oh, my code has added the where column = true, must have gone through the wrong IF...".

推荐答案

这是关于 SQL 调试的一个最常见的误区.我需要在准备后查看查询才能判断是否发生了错误".事实是,你不,我会告诉你原因.

That's the single most common myth about SQL debugging. "I need to see the query after preparation to be able to tell if an error occurred". The fact is, you don't, and I'll tell you why.

准备好查询后,可以将占位符视为有效字符串/整数.你不在乎里面有什么.

Once a query has been prepared, the placeholder can be considered as a valid string/integer. You don't care what's in it.

此外,如果您正确设置了 PDO,您将获得详细的 PDOException 详细说明您遇到的错误以及错误发生位置的完整回溯,以及您获得错误字符串来自 MySQL,这使得语法错误很容易被发现.

Also, if you set up PDO correctly, you'll get a detailed PDOException detailing the error you've had along with a complete backtrace of where the error happened, plus you get the error string from MySQL, which makes syntax errors very easy to find.

要启用 PDO 异常并禁用模拟准备:

To enable PDO Exceptions and disable emulated prepares:

$pdo = new PDO("mysql:host=localhost;dbname=database_name", "user", "password");
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);

这篇关于PDO 调试 - 绑定后查看查询?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:PDO 调试 - 绑定后查看查询?

基础教程推荐