Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In PHP with PDO, how to check the final SQL parametrized query? [duplicate]

In PHP, when accessing MySQL database with PDO with parametrized query, how can you check the final query (after having replaced all tokens)?

Is there a way to check what gets really executed by the database?

like image 644
JB Hurteaux Avatar asked Sep 30 '22 00:09

JB Hurteaux


People also ask

How to check query in PDO?

You need to set the error mode attribute PDO::ATTR_ERRMODE to PDO::ERRMODE_EXCEPTION. And since you expect the exception to be thrown by the prepare() method you should disable the PDO::ATTR_EMULATE_PREPARES* feature. Otherwise the MySQL server doesn't "see" the statement until it's executed.

How check PDO query is successful in PHP?

de.php.net/manual/en/pdostatement.execute.php says: Returns TRUE on success or FALSE on failure. - So bind it to a variable, e.g. $success = $STH->execute($params); and check that variable against true or false .

How can I get the last updated record in PHP?

You can simply do a query like this: SELECT * FROM `tblxdetails` ORDER BY `id` DESC LIMIT 1 ; and it will give you the last added field only Though this will only get you the last one added, if there is editing of records going on then use the previous code given.


2 Answers

So I think I'll finally answer my own question in order to have a full solution for the record. But have to thank Ben James and Kailash Badu which provided the clues for this.

Short Answer
As mentioned by Ben James: NO.
The full SQL query does not exist on the PHP side, because the query-with-tokens and the parameters are sent separately to the database. Only on the database side the full query exists.

Even trying to create a function to replace tokens on the PHP side would not guarantee the replacement process is the same as the SQL one (tricky stuff like token-type, bindValue vs bindParam, ...)

Workaround
This is where I elaborate on Kailash Badu's answer. By logging all SQL queries, we can see what is really run on the server. With mySQL, this can be done by updating the my.cnf (or my.ini in my case with Wamp server), and adding a line like:

log=[REPLACE_BY_PATH]/[REPLACE_BY_FILE_NAME]

Just do not run this in production!!!

like image 61
JB Hurteaux Avatar answered Oct 13 '22 02:10

JB Hurteaux


You might be able to use PDOStatement->debugDumpParams. See the PHP documentation .

like image 38
Michael Avatar answered Oct 13 '22 01:10

Michael