PDO Debugging - View Query AFTER Bind?

debugging, mysql, pdo, php

Solution

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.

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.

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);

Problem

Possible Duplicate: Retrieve (or simulate) full query from PDO prepared statement 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? Is there maybe a way to ask the server "what was the last query", or tell PDO "show me what you sent"? 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. Using `bindValue(":fieldValue", $value);` if that makes a difference. EDIT 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...".

Original source

Related problems