Home » Php » php – PDO, Mysql and native prepared statements

php – PDO, Mysql and native prepared statements

Posted by: admin July 12, 2020 Leave a comment


The understanding of PDO that I’ve had up till now is that PDO will use real prepared statements where it can, and emulate them where it can’t. I also understood that where mysql was concerned, real prepared statements would be used provided you were communicating with a version of mysql that supported them.

In fact the PHP manual page for the MySQL PDO driver says as much. http://php.net/manual/en/ref.pdo-mysql.php

However, on another SO question I was helping out on How to replace all occurencies of char with elements from array? , someone made the comment that this is not true, and that in fact PDO emulates prepared statements when talking to a MySQL database.

I’ve not had much luck finding evidence to back the claims made there up, but I did discover that there is a PDO::ATTR_EMULATE_PREPARES attribute that can be configured to toggle prepared statement emulation.

so what’s the truth of the matter? Does PDO really not use prepared statements with mysql? If not, can it be forced to do so, and if so, should you do that? I’ve always assumed that as mysql has real prepared statements that PDO would use them, as claimed in the manual. Is the manual inaccurate?

EDIT TO ADD: I have read a few articles recently that at least give a decent rationale as to why real prepared queries are disabled by default. PHP scripts tend to be short lived and only run long enough to generate a response to a request, after which all their resources are deallocated. For any query you only execute once per request you’d actually have to execute 2 SQL commands (The prepare command and the execute command) so for any prepared statement that’s only executed once you’ll probably actually get slightly worse performance than with the emulated prepared statement. For queries that must be run in a loop real prepared statements will probably perform better but such cases are relatively rare in the kind of request/response model PHP is typically used for.

I still think real prepared statements are preferable but at least I have a reasonable explanation as to why PDO uses emulated queries by default.

How to&Answers:

Does PDO really not use prepared statements with mysql?

Yes, by default (at least with version I tested) but native mode can be turned on manually.

If not, can it be forced to do so

By employing PDO::ATTR_EMULATE_PREPARES setting, the name is pretty self-explanatory.

$dbh->setAttribute( PDO::ATTR_EMULATE_PREPARES, false );

should you do that?

That’s hardest question of them all.
Well, I’d say – yes, you should. If you choose PDO as your db driver, there is no point in using it in the emulation mode.