Robbie Robbie - 2 years ago 130
SQL Question

Freeing up PDO prepared statements (DEALLOCATE PREPARE)

Should PDO prepared statements be freed up after use? And if so, how? Specifically I'm asking about MySQL - how can you, and should you, call

though PDO. (Edit: To clarify, this question is not referring to emulated prepares, but real prepares. )

Also - will this free the results set (when large)?


I have seen code along the lines of

$stmnt = $db->prepare($sql);
$stmnt = null;

which led me to wondering what this does, when, and if f
would be different?

The manual indicates that

When the query is prepared, the database will analyze, compile and
optimize its plan for executing the query. [...] By using a prepared
statement the application avoids repeating the
analyze/compile/optimize cycle.

which tends to suggest you should unallocate the statement, and MySQL has the capability. So,

  1. Can you call
    , and how

  2. Should you do it?

  3. And can anyone confirm that setting statement to null (or unsetting the statement) will do the same as "free_result" for mysql_ and mysqli_?

  4. Does it happen immediately, or does it wait for garbage collector to kick in?

For completeness, another SO question referring to "free_result" and "close" functions for
suggests that freeing the statement actually adds time (unless you have large memory usage and need the space). But "free_result" is different from freeing the SQL server from having the prepared statment cached.

Answer Source

Should PDO prepared statements be freed up after use? And if so, how?

In the context of MySQL? No. Why?

PDO emulates prepared statements by default. This means that PDO itself does the parameter replacement, escaping, etc, and sends chunks of SQL down the line instead of using native prepared statements.

While you can turn it on, you still don't need to expressly close the handle unless you are also using unbuffered queries. Merely letting the statement handle go out of scope or setting it to null will not close the cursor. Again, this only matters if you're using unbuffered queries. If you are not, then letting it go out of scope or setting it to null is enough to close the handle cleanly.

You also linked to DEALLOCATE PREPARE. That syntax is only needed when manually calling PREPARE with an SQL string. This is a completely and totally separate action than MySQL C-level API-based prepared statements, which is what PDO_MYSQL is using. (Okay, maybe you're using mysqlnd, but it's effectively the same thing.)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download