Can a PDO be stored in a session?

I have two questions:

  • To benefit from prepared PDO statements, should I first prepare the statement using the PDO object:

    $ statement = $ pdo-> prepare ($ query, $ bindings);

and then save this $ statement in $ _SESSION and reuse that statement, or should I do the same (PDO :: prepare) again the next time I want to execute the same query (with different values ​​for the bindings)?

  • Is it useful to store a PDO in $ _SESSION when using PDO :: ATTR_PERSISTENT when creating a PDO?
+7
source share
2 answers

You should not store PDOs in sessions.

The best (and only right) way to use PDOs is to create them for every request to the server.

The advantage of prepared queries is 2 ways:

  • When executing the same request several times there is an advantage in speed
  • It is possible to bind parameters to prevent SQL injection.

When storing a PDO resource in a session, an open connection to the database will be created, as requests from different clients arrive. PDO does a connection pool, trying to minimize database connections, but still with some connections open to speed. By keeping pdo connections in the session, this mechanism is killed. And performance will suffer.

+8
source

In fact, "You cannot serialize or unialize PDOStatement instances" (quoting the actual exception message). Here's the full message:

PHP Fatal error: Uncaught exception 'PDOException' with message 'You cannot serialize or unserialize PDOStatement instances' in [no active file]:0 Stack trace: #0 [internal function]: PDOStatement->__sleep() #1 {main} thrown in [no active file] on line 0 

How why - he already answered here .

+1
source